summaryrefslogtreecommitdiff
path: root/indoteknik_api/controllers/api_v1/auth.py
blob: e51431b14093e36cb72324710797a7e60eb3e6a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from .. import controller
from odoo import http
from odoo.http import request
from odoo.tools.config import config


class Auth(controller.Controller):
    prefix = '/api/v1/'
    
    @http.route(prefix + 'auth/login', auth='public', methods=['POST'], csrf=False)
    def login(self, **kw):
        if not self.authenticate():
            return self.response(code=401, description='Unauthorized')
        
        email = kw.get('email')
        password = kw.get('password')
        if not email or not password:
            return self.response(code=400, description='email and password is required')
        
        user = self.get_user(email)
        if user and not user.active:
            return self.response({
                'is_auth': False,
                'reason': 'NOT_ACTIVE'
            })
        
        try:
            uid = request.session.authenticate(config.get('db_name'), email, password)
            user = request.env['res.users'].browse(uid)
            return self.response({
                'is_auth': True, 
                'user': {
                    'id': user.id,
                    'name': user.name,
                    'email': user.login,
                    'external': user.share
                }
            })
        except:
            return self.response({
                'is_auth': False,
                'reason': 'NOT_FOUND'
            })
    
    @http.route(prefix + 'auth/register', auth='public', methods=['POST'], csrf=False)
    def register(self, **kw):
        if not self.authenticate():
            return self.response(code=401, description='Unauthorized')
        
        name = kw.get('name')
        email = kw.get('email')
        password = kw.get('password')
        if not name or not email or not password:
            return self.response(code=400, description='email and password is required')
        
        user = self.get_user(email)
        
        if user:
            return self.response({
                'register': False,
                'reason': 'EMAIL_USED'
            })
        
        user = request.env['res.users'].create({
            'name': name,
            'login': email,
            'password': password,
            'active': False,
            'sel_groups_1_9_10': 9
        })
        
        return self.response({'register': True})
    
    def get_user(self, email):
        return request.env['res.users'].search([('login', '=', email), ('active', 'in', [True, False])])