Completed
Push — master ( f91963...0831bf )
by Glenn
45s
created

login_user()   C

Complexity

Conditions 7

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
dl 0
loc 40
rs 5.5
c 0
b 0
f 0
1
import jwt, random, sys 
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(privileges.privilegeID == 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
                        if sys.version_info.major == 3:
66
                        	unicode = str
67
                        token = unicode(token_raw,'utf-8')
68
                        return {'Authorization token': token, 'username': username}
69
                    else:
70
                        log("User triggered error login failed", "HIGH", "FAIL")
71
                        return {'Authorization token': ''}
72
                else:
73
                    log("User triggered error login failed", "HIGH", "FAIL")
74
                    return {'Authorization token': ''}
75
            else:
76
                log("User triggered error login failed", "HIGH", "FAIL")
77
                return {'Authorization token': ''}
78
    except NoResultFound:
79
        log("User triggered error login failed", "HIGH", "FAIL")
80
        return {'Authorization token': ''}
81
82
83
def list_privileges():
84
    log("User requested privileges items", "MEDIUM", "PASS")
85
    result = privileges.query.filter(privileges.privilegeID != "1").paginate(1, 500, False)
86
    return result
87
88
89
def create_user(data):
90
    log("A new user created", "MEDIUM", "PASS")
91
    my_secure_rng = random.SystemRandom()
92
    val_num(data.get('privilege'))
93
    pincode = my_secure_rng.randrange(10000000, 99999999)
94
    username = pincode
95
    email = data.get('email')
96
    access = "False"
97
    activated = "False"
98
    privilege_id = 0
99
    # New users can only edit:read:delete
100
    if data.get('privilege') == 1:
101
        log("User triggered error creating new user", "MEDIUM", "FAIL")
102
        return {'message': 'User could not be created'}
103
    else:
104
        privilege_id = data.get('privilege')
105
    password = ""
106
    user = users(privilege_id, pincode, username, password, access, activated, email)
107
    db.session.add(user)
108
    db.session.commit()
109
    result = users.query.filter(users.email == email).one()
110
111
    # Add user to default groupmember issue #422
112
    groupmember = groupmembers.query.order_by(desc(groupmembers.memberID)).first()
113
    groupmemberUser = groupmembers(groupmember.memberID + 1, result.userID, groupmember.groupID, groupmember.ownerID, None)
114
    db.session.add(groupmemberUser)
115
    db.session.commit()
116
117
    return result
118
119
120
def manage_user(user_id, data):
121
    log("Manage user triggered", "HIGH", "PASS")
122
    val_num(user_id)
123
    val_alpha(data.get('active'))
124
    status_activated = data.get('active')
125
    result = users.query.filter(users.userID == user_id).one()
126
    if users.query.filter(users.userID == user_id).one():
127
        result.access = status_activated
128
        db.session.add(result)
129
        db.session.commit()
130
        return {'message': 'User successfully managed'}
131
    else:
132
        log("User triggered error managing failed", "HIGH", "FAIL")
133
        return {'message': 'User could not be managed'}
134
135
136
def list_users():
137
    log("Overview of list users triggered", "HIGH", "PASS")
138
    result = users.query.paginate(1, 50, False)
139
    return result
140
141