]>
Commit | Line | Data |
---|---|---|
11fdf7f2 TL |
1 | # -*- coding: utf-8 -*- |
2 | from __future__ import absolute_import | |
3 | ||
9f95a23c | 4 | import logging |
11fdf7f2 | 5 | import cherrypy |
11fdf7f2 TL |
6 | |
7 | from . import ApiController, RESTController | |
9f95a23c | 8 | from .. import mgr |
11fdf7f2 TL |
9 | from ..exceptions import DashboardException |
10 | from ..services.auth import AuthManager, JwtManager | |
9f95a23c TL |
11 | |
12 | ||
13 | logger = logging.getLogger('controllers.auth') | |
11fdf7f2 TL |
14 | |
15 | ||
16 | @ApiController('/auth', secure=False) | |
17 | class Auth(RESTController): | |
18 | """ | |
19 | Provide authenticates and returns JWT token. | |
20 | """ | |
21 | ||
22 | def create(self, username, password): | |
9f95a23c TL |
23 | user_data = AuthManager.authenticate(username, password) |
24 | user_perms, pwd_expiration_date, pwd_update_required = None, None, None | |
25 | if user_data: | |
26 | user_perms = user_data.get('permissions') | |
27 | pwd_expiration_date = user_data.get('pwdExpirationDate', None) | |
28 | pwd_update_required = user_data.get('pwdUpdateRequired', False) | |
29 | ||
11fdf7f2 TL |
30 | if user_perms is not None: |
31 | logger.debug('Login successful') | |
32 | token = JwtManager.gen_token(username) | |
33 | token = token.decode('utf-8') | |
11fdf7f2 TL |
34 | cherrypy.response.headers['Authorization'] = "Bearer: {}".format(token) |
35 | return { | |
36 | 'token': token, | |
37 | 'username': username, | |
9f95a23c TL |
38 | 'permissions': user_perms, |
39 | 'pwdExpirationDate': pwd_expiration_date, | |
40 | 'sso': mgr.SSO_DB.protocol == 'saml2', | |
41 | 'pwdUpdateRequired': pwd_update_required | |
11fdf7f2 TL |
42 | } |
43 | ||
44 | logger.debug('Login failed') | |
45 | raise DashboardException(msg='Invalid credentials', | |
46 | code='invalid_credentials', | |
47 | component='auth') | |
48 | ||
49 | @RESTController.Collection('POST') | |
50 | def logout(self): | |
51 | logger.debug('Logout successful') | |
52 | token = JwtManager.get_token_from_header() | |
53 | JwtManager.blacklist_token(token) | |
54 | redirect_url = '#/login' | |
55 | if mgr.SSO_DB.protocol == 'saml2': | |
56 | redirect_url = 'auth/saml2/slo' | |
57 | return { | |
58 | 'redirect_url': redirect_url | |
59 | } | |
60 | ||
61 | def _get_login_url(self): | |
62 | if mgr.SSO_DB.protocol == 'saml2': | |
63 | return 'auth/saml2/login' | |
64 | return '#/login' | |
65 | ||
66 | @RESTController.Collection('POST') | |
67 | def check(self, token): | |
68 | if token: | |
9f95a23c TL |
69 | user = JwtManager.get_user(token) |
70 | if user: | |
71 | return { | |
72 | 'username': user.username, | |
73 | 'permissions': user.permissions_dict(), | |
74 | 'sso': mgr.SSO_DB.protocol == 'saml2', | |
75 | 'pwdUpdateRequired': user.pwd_update_required | |
76 | } | |
11fdf7f2 | 77 | return { |
9f95a23c | 78 | 'login_url': self._get_login_url(), |
11fdf7f2 | 79 | } |