Completed
Push — master ( c53f8e...369eeb )
by Glenn
52s
created

create_user()   B

Complexity

Conditions 2

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 29
rs 8.8571
cc 2
1
import jwt, secrets
2
3
from flask_bcrypt import generate_password_hash, check_password_hash
4
from datetime import date, datetime, timedelta
0 ignored issues
show
Unused Code introduced by MACBOOK
Unused date imported from datetime
Loading history...
5
from sqlalchemy.orm.exc import NoResultFound
6
from sqlalchemy import desc
7
8
from skf import settings
9
from skf.database import db
10
from skf.database.users import users
11
from skf.database.groupmembers import groupmembers
12
from skf.database.privileges import privileges
13
from skf.api.security import log, val_num, val_alpha, val_alpha_num
14
15
16
def activate_user(user_id, data):
17
    log("User is activated", "HIGH", "PASS")
18
    val_num(user_id)
19
    val_num(data.get('accessToken'))
20
    val_alpha_num(data.get('username'))
21
    username = data.get('username')
22
    username = username.replace(" ", "")
23
    result = users.query.filter(users.userID == user_id).one()
24
    if result.activated == "False":
25
        if result.email == data.get('email'):
26
            if data.get('password') == data.get('repassword'):
27
                if data.get('accessToken') == result.accessToken:
28
                    pw_hash = generate_password_hash(data.get('password')).decode('utf-8')
29
                    result.password = pw_hash
30
                    result.access = "True"
31
                    result.activated = "True"
32
                    result.userName = username
33
                    db.session.add(result)
34
                    db.session.commit()
35
                    return {'message': 'User successfully activated'}
36
    else:
37
        log("User triggered error activation failed", "HIGH", "FAIL")
38
        return {'message': 'User could not be activated'}
39
40
41
def login_user(data):
42
    log("User successfully logedin", "HIGH", "PASS")
43
    val_alpha_num(data.get('username'))
44
    username = data.get('username')
45
    try:
46
        if (users.query.filter(users.userName == username).one()):
47
            user = users.query.filter(users.userName == username).one()
48
            if (user.activated == "True"):
49
                if (user.access == "True"):
50
                    if check_password_hash(user.password, data.get('password')):
51
                        priv_user = privileges.query.filter(str(user.privilegeID)).first()
52
                        payload = {
53
                            # userid
54
                            'UserId': user.userID,
55
                            #issued at
56
                            'iat': datetime.utcnow(),
57
                            #privileges
58
                            'privilege': priv_user.privilege,
59
                            #expiry
60
                            'exp': datetime.utcnow() + timedelta(minutes=120)
61
                            #claims for access api calls
62
                            #'claims': 'kb/items/update,project/items,non/existing/bla,'
63
                        }
64
                        token_raw = jwt.encode(payload, settings.JWT_SECRET, algorithm='HS256')
65
                        token = str(token_raw,'utf-8')
66
                        return {'Authorization token': token, 'username': username}
67
                    else:
68
                        log("User triggered error login failed", "HIGH", "FAIL")
69
                        return {'Authorization token': ''}
70
                else:
71
                    log("User triggered error login failed", "HIGH", "FAIL")
72
                    return {'Authorization token': ''}
73
            else:
74
                log("User triggered error login failed", "HIGH", "FAIL")
75
                return {'Authorization token': ''}
76
    except NoResultFound:
77
        log("User triggered error login failed", "HIGH", "FAIL")
78
        return {'Authorization token': ''}
79
80
81
def create_user(data):
82
    log("A new user created", "MEDIUM", "PASS")
83
    my_secure_rng = secrets.SystemRandom()
84
    val_num(data.get('privilege'))
85
    pincode = my_secure_rng.randrange(10000000, 99999999)
86
    username = pincode
87
    email = data.get('email')
88
    access = "False"
89
    activated = "False"
90
    privilege_id = 0
91
    # New users can only edit:read:delete
92
    if data.get('privilege') == 1:
93
        log("User triggered error creating new user", "MEDIUM", "FAIL")
94
        return {'message': 'User could not be created'}
95
    else:
96
        privilege_id = data.get('privilege')
97
    password = ""
98
    user = users(privilege_id, pincode, username, password, access, activated, email)
99
    db.session.add(user)
100
    db.session.commit()
101
    result = users.query.filter(users.email == email).one()
102
103
    # Add user to default groupmember issue #422
104
    groupmember = groupmembers.query.order_by(desc(groupmembers.memberID)).first()
105
    groupmemberUser = groupmembers(groupmember.memberID + 1, result.userID, groupmember.groupID, groupmember.ownerID, None)
106
    db.session.add(groupmemberUser)
107
    db.session.commit()
108
109
    return result
110
111
112
def manage_user(user_id, data):
113
    log("Manage user triggered", "HIGH", "PASS")
114
    val_num(user_id)
115
    val_alpha(data.get('active'))
116
    status_activated = data.get('active')
117
    result = users.query.filter(users.userID == user_id).one()
118
    if users.query.filter(users.userID == user_id).one():
119
        result.access = status_activated
120
        db.session.add(result)
121
        db.session.commit()
122
        return {'message': 'User successfully managed'}
123
    else:
124
        log("User triggered error managing failed", "HIGH", "FAIL")
125
        return {'message': 'User could not be managed'}
126
127
128
def list_users():
129
    log("Overview of list users triggered", "HIGH", "PASS")
130
    result = users.query.paginate(1, 50, False)
131
    return result
132
133