Example #1
0
 def wrapper(*args, **kwargs):
     token = request.args.get('token')
     try:
         jwt.decode(token, booksapp.config['SECRET_KEY'])
         return f(*args, **kwargs)
     except:
         return jsonify({'error': 'Need a valid token to view this page'}, 401)
Example #2
0
 def put(self):
     try:
         parser = reqparse.RequestParser()
         parser.add_argument('oldPassword', required=True, help='oldPassword is Required')
         parser.add_argument('newPassword', required=True, help='newPassword is Required')
         args = parser.parse_args()
         x = request.headers.get('Authorization')
         try:
             x = x[2:-1]
         except TypeError:
             print(x)
         access_token = jwt.decode(x, 'secret', algorithms='HS256', verify=False)
         cursor = db.cursor()
         cursor.execute('SELECT Password FROM users WHERE UserName = %s', (access_token['UserName']))
         pwd = cursor.fetchone()
         if (pwd[0] == args['oldPassword']):
             try:
                 cursor.execute('UPDATE users SET Password = %s WHERE UserName = %s',
                                (args['newPassword'], access_token['UserName']))
             except InterfaceError as e:
                 CreateApi.reAssignDb()
                 print(e)
             except Exception as e:
                 return {"message": "Please try again!"}, 500
             db.commit()
             return {"message": "Password changed successfully"}
         else:
             return {"message": "Password does not match"}, 500
     except InterfaceError as e:
         CreateApi.reAssignDb()
         print(e)
     except Exception as e:
         print(e)
Example #3
0
 def register(access_token, func_name, msg):
     try:
         if msg is True:
             d = datetime.datetime.today().strftime('%Y-%m-%d')
             t = datetime.datetime.today().strftime('%H:%M:%S')
             x = access_token
             try:
                 x = x[2:-1]
             except TypeError:
                 print(x)
             access_token = jwt.decode(x,
                                       'secret',
                                       algorithms='HS256',
                                       verify=False)
             cursor = db.cursor()
             row_count = cursor.execute(
                 "Insert into logs(DATE,TIME,USER,ACTION) VALUES ('" + d +
                 "','" + t + "','" + access_token['UserName'] + "','" +
                 func_name + "')")
             if row_count > 0:
                 print('Logged Succesfully')
                 message = True
             else:
                 print('Log Failure for: ' + access_token['UserName'] +
                       ' ' + func_name)
                 message = False
             db.commit()
             return (message)
     except InterfaceError as e:
         CreateApi.reAssignDb()
         print(e)
     except Exception as e:
         print(e)
Example #4
0
def mail_verified(token):

    # This form does not use the FlaskForm-extension. This is because of a bug with validation that made the JWT-token invalid and the form would not validate correctly,
    # causing faulty passwords to be saved to the database. Security is instead provided by the URL being passed to the users external email inbox, proving they are the owner
    # of the account.

    # Verified the token is still valid, by decrypting it and checking it against the database to see if the decrypted token matches a user
    user = jwt.decode(token, key=os.getenv('SECRET_KEY'))["reset_password"]
    token_valid = User.objects(email=user).first()
    password = request.form.get("password")

    if request.method == 'POST':
        # If a post occurs, check the validity of the token against the DB of registered users.

        if token_valid is None:
            # This route triggers if the token is expired or otherwise faulty and redirects to the login page. Legitimate users can from there request a new reset-email.
            flash("Invalid token, password reset request denied.")
            return redirect(url_for('login'))
        else:
            # If a token matching the JWT-token payload has been found, we hash  the current input and save it to the database.
            token_valid.password = generate_password_hash(password)
            token_valid.save().reload()
            # User feedback and redirect
            flash("Your password has been changed!")
            login_user(token_valid)
            return redirect(url_for('profile'))
    return render_template('verified_password_change.html', token=token)
Example #5
0
 def verify_auth_token(token):
     try:
         data = jwt.decode(token,
                           app.config['SECRET_KEY'],
                           algorithms=['HS256'])
     except:
         return
     return User.query.get(data['id'])
Example #6
0
 def verify_auth_token_legacy2(token):
     try:
         data = jwt.decode(token,
                           current_app.config['SECRET_KEY'],
                           True,
                           algorithms=['HS256'])
     except:
         return None
     return User.query.get(data['id'])
Example #7
0
def decode_auth_token(auth_token, jwt_key):
    try:
        payload = jwt.decode(auth_token, jwt_key)

        return payload['sub']
    except jwt.ExpiredSignatureError:
        return JWT_TOKEN_EXPIRED
    except jwt.InvalidTokenError:
        return JWT_INVALID_TOKEN
Example #8
0
def verify_token(token):
    """
    Token verification
    :param token: authorization token
    """
    decoded = jwt.decode(token, current_app.config["SECRET_KEY"], verify=True)
    current_user_id = decoded['identity']
    if not current_user_id is None:
        g.current_user = current_user_id
        return True
    return False
 def post(self):
     x = request.headers.get('Authorization')
     try:
         x = x[2:-1]
     except TypeError:
         print(x)
     print(x)
     access_token = jwt.decode(x,
                               'secret',
                               algorithms='HS256',
                               verify=False)
     print(access_token)
 def post(self):
     try:
         x = request.headers.get('Authorization')
         try:
             x = x[2:-1]
         except TypeError:
             print(x)
         access_token = jwt.decode(x,
                                   'secret',
                                   algorithms='HS256',
                                   verify=False)
         parser = reqparse.RequestParser()
         parser.add_argument('UserName',
                             required=True,
                             help='UserName is Required')
         parser.add_argument('Role', required=True, help='Role is Required')
         args = parser.parse_args()
         cursor = db.cursor()
         try:
             row_count = cursor.execute(
                 "Insert into users(UserName,Password,Role,LASTDATE,LASTUSER) VALUES (%s,%s,%s,%s,%s)",
                 (args['UserName'], '123456', args['Role'],
                  datetime.datetime.now(), access_token['UserName']))
         except InterfaceError as e:
             CreateApi.reAssignDb()
             print(e)
         except Exception as e:
             print(e.args[1])
             if ("Duplicate entry" in e.args[1]):
                 raise BadRequest("user already exists")
             else:
                 raise BadRequest(str(e.args[1]))
         row = cursor.fetchone()
         l = Log
         x = True
         x = l.register(request.headers.get('Authorization'),
                        'Add User:%s' % args['UserName'], True)
         if x == True:
             db.commit()
         message = {
             'message': 'adduser',
             'data': {
                 "UserName": args['UserName'],
                 "Role": args['Role']
             }
         }
         return (message)
     except InterfaceError as e:
         CreateApi.reAssignDb()
         print(e)
     except Exception as e:
         print(e)
Example #11
0
def decode_auth_token(auth_token):
    try:
        payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'))
        return payload['identity'], None
    except jwt.ExpiredSignatureError:
        error_message = 'Signature expired. Please log in again.'
    except jwt.InvalidTokenError:
        error_message = 'Invalid token. Please log in again.'
    except:
        error_message = 'Unknown JWT Authorization Error'
    print("Auth error", error_message)
    make_response(jsonify({'error': error_message}), 401)
    return None, error_message
Example #12
0
        def decorated(*args, **kwargs):
            token = None
            if 'x-access-token' in request.headers:
                token = request.headers['x-access-token']
            if not token:
                return ({"message": "token is missing"}), 401

            data = jwt.decode(token, 'OLURIN ANUOLUWAPO')
            try:
                current_user = UserModel().get_one('userid', data['user_id'])
            except:
                return ({"message": "token is invalid"}), 401

            return f(current_user, *args, **kwargs)
 def decode_token(token):
   """
   Decode token method
   """
   re = {'data': {}, 'error': {}}
   try:
     payload = jwt.decode(token, os.getenv('JWT_SECRET_KEY'))
     re['data'] = {'player_id': payload['sub']}
     return re
   except jwt.ExpiredSignatureError as e1:
     re['error'] = {'message': 'token expired, please login again'}
     return re
   except jwt.InvalidTokenError:
     re['error'] = {'message': 'Invalid token, please try again with a new token'}
     return re
Example #14
0
    def decorated(*args, **kwargs):
        secret = app.config['SECRET_KEY']
        auth = request.headers.get('Authorization', None)
        if not auth:
            return jsonify({
                'code': 'authorization_header_missing',
                'description': 'Authorization header is expected'
            }), 401

        parts = auth.split()

        if parts[0].lower() != 'bearer':
            return jsonify({
                'code':
                'invalid_header',
                'description':
                'Authorization header must start with Bearer'
            }), 401
        elif len(parts) == 1:
            return jsonify({
                'code': 'invalid_header',
                'description': 'Token not found'
            }), 401
        elif len(parts) > 2:
            return jsonify({
                'code':
                'invalid_header',
                'description':
                'Authorization header must be Bearer + \s + token'
            }), 401

        token = parts[1]
        try:
            payload = jwt.decode(token, secret)

        except jwt.ExpiredSignature:
            return jsonify({
                'code': 'token_expired',
                'description': 'token is expired'
            }), 401
        except jwt.DecodeError:
            return jsonify({
                'code': 'token_invalid_signature: {}'.format(token),
                'description': 'Token signature is invalid'
            }), 401

        g.current_user = user = payload
        return f(*args, **kwargs)
 def put(self):
     try:
         x = request.headers.get('Authorization')
         try:
             x = x[2:-1]
         except TypeError:
             print(x)
         access_token = jwt.decode(x,
                                   'secret',
                                   algorithms='HS256',
                                   verify=False)
         parser = reqparse.RequestParser()
         parser.add_argument('Role')
         parser.add_argument('UserName')
         args = parser.parse_args()
         cursor = db.cursor()
         row_count = cursor.execute(
             'UPDATE users SET Role = %s ,LASTDATE = %s ,LASTUSER = %s WHERE UserName = %s',
             (args['Role'], datetime.datetime.now(),
              access_token['UserName'], args['UserName']))
         if row_count > 0:
             l = Log
             x = l.register(
                 request.headers.get('Authorization'),
                 'UPDATE Role: %s of User: %s' %
                 (args['Role'], args['UserName']), True)
             if x == True:
                 db.commit()
                 return ({
                     'message': 'updateuser',
                     'data': {
                         "UserName": args['UserName'],
                         "Role": args['Role']
                     }
                 })
             else:
                 raise BadRequest("Try Again")
         else:
             raise BadRequest("Try Again")
     except InterfaceError as e:
         CreateApi.reAssignDb()
         print(e)
     except Exception as e:
         print(e)
Example #16
0
def decode_access_token(access_token):
    """
    Validates the user access token

    :param str access_token: The access token tp be decoded
    :return: integer|string
    """
    try:
        payload = jwt.decode(access_token, APP.config.get('SECRET_KEY'))
        is_blacklisted_token = BlacklistToken.check_blacklisted(access_token)
        if is_blacklisted_token:
            return 'Token blacklisted. Please log in again.'
        public_id = payload['sub']
        user = User.query.filter_by(public_id=public_id).first()
        return user.id
    except jwt.ExpiredSignatureError:
        return 'Signature expired. Please log in again.'
    except jwt.InvalidTokenError:
        return 'Invalid token. Please log in again.'
Example #17
0
 def decode_auth_token(auth_token):
     """
     验证Token
     :param auth_token:
     :return: integer|string
     """
     try:
         payload = jwt.decode(auth_token,
                              config.SECRET_KEY,
                              options={'verify_exp': False})
         if 'exp' in payload and 'data' in payload and 'user_id' in payload[
                 'data']:
             return payload
         else:
             return 1004
     except jwt.ExpiredSignatureError:
         return 1005  # 过期
     except jwt.InvalidTokenError:
         return 1004  # 无效
 def get(self):
     try:
         x = request.headers.get('Authorization')
         try:
             x = x[2:-1]
         except TypeError:
             print(x)
         access_token = jwt.decode(x,
                                   'secret',
                                   algorithms='HS256',
                                   verify=False)
         cursor = db.cursor()
         message = []
         row_count = cursor.execute("SELECT UserName,role from users")
         row = cursor.fetchall()
         for item in row:
             message.append({"UserName": item[0], "Role": item[1]})
         return flask.jsonify(message)
     except InterfaceError as e:
         CreateApi.reAssignDb()
         print(e)
     except Exception as e:
         print(e)
 def delete(self):
     try:
         x = flask.request.headers.get('Authorization')
         try:
             x = x[2:-1]
         except TypeError:
             print(x)
         access_token = jwt.decode(x,
                                   'secret',
                                   algorithms='HS256',
                                   verify=False)
         try:
             data = flask.request.get_json()
             cursor = db.cursor()
             cursor.execute("DELETE from users where UserName = %s ",
                            (data['UserName']))
         except InterfaceError as e:
             CreateApi.reAssignDb()
             print(e)
         except Exception as e:
             raise BadRequest(str(e))
         l = Log
         x = l.register(request.headers.get('Authorization'),
                        'Delete user: %s' % (data['UserName']), True)
         if x == True:
             db.commit()
             return ({
                 'message': 'deleteuser',
             })
         else:
             raise BadRequest("Try Again")
     except InterfaceError as e:
         CreateApi.reAssignDb()
         print(e)
     except Exception as e:
         print(e)
Example #20
0
def decode_token(token):
    try:
        jwt.decode(token,app.config.get("SECRET_KEY"))
        return True
    except:
        return False
Example #21
0
    def get(self):
        try:
            x = request.headers.get('Authorization')
            try:
                x = x[2:-1]
            except TypeError:
                print(x)
            access_token = jwt.decode(x,
                                      'secret',
                                      algorithms='HS256',
                                      verify=False)
            user = request.args.get('user')
            print(user)
            if (user == ""):
                admin = []
                war = []
                pur = []
                warehouseworker = []
                engineering = []
                sawcutter = []
                cursor = db.cursor()
                admin_count = cursor.execute(
                    "SELECT UserName from users where ROLE ='admin'")
                ad = cursor.fetchall()
                for i in range(0, admin_count):
                    admin.append(ad[i])
                war_count = cursor.execute(
                    "SELECT UserName from users where ROLE ='warehouse'")
                wa = cursor.fetchall()
                for i in range(0, war_count):
                    war.append(wa[i])
                pur_count = cursor.execute(
                    "SELECT UserName from users where ROLE ='purchasing'")
                pu = cursor.fetchall()
                for i in range(0, pur_count):
                    pur.append(pu[i])
                warwor_count = cursor.execute(
                    "SELECT UserName from users where ROLE ='materialHandler'")
                wawor = cursor.fetchall()
                for i in range(0, warwor_count):
                    warehouseworker.append(wawor[i])
                eng_count = cursor.execute(
                    "SELECT UserName from users where ROLE ='engineering'")
                eng = cursor.fetchall()
                for i in range(0, eng_count):
                    engineering.append(eng[i])
                saw_count = cursor.execute(
                    "SELECT UserName from users where ROLE ='sawcutter'")
                saw = cursor.fetchall()
                for i in range(0, saw_count):
                    sawcutter.append(saw[i])

                message = {
                    'admin': admin,
                    'warehouse': war,
                    'purchasing': pur,
                    'warehouseworker': warehouseworker,
                    'engineering': engineering,
                    'sawcutter': sawcutter
                }
                return message
            else:
                message = []
                cursor = db.cursor()
                row_count = cursor.execute(
                    'SELECT DATE,TIME,USER,ACTION from logs where USER = %s',
                    (str(user)))
                row = cursor.fetchall()
                print(row_count)
                for i in range(0, row_count):
                    message.append({
                        "DATE": row[i][0],
                        "TIME": str(row[i][1]),
                        "USER": row[i][2],
                        "ACTION": row[i][3]
                    })
                return flask.jsonify(message)
        except InterfaceError as e:
            CreateApi.reAssignDb()
            print(e)
        except Exception as e:
            print(e)
Example #22
0
    def decorated(*args, **kwargs):
        # check that the Authorization header is set
        authorization_token = request.headers.get('Authorization')
        if not authorization_token:
            response = jsonify({
                "status": "fail",
                "data": {
                    "message": "Bad request. Header does not contain"
                            " authorization token"
                }
            })
            response.status_code = 400
            return response

        # validates the word bearer is in the token
        if 'bearer ' not in authorization_token.lower():
            response = jsonify({
                "status": "fail",
                "data": {
                    "message": "Invalid Token. The token should begin with"
                            " 'Bearer '"
                }
            })
            response.status_code = 400
            return response

        unauthorized_response = jsonify({
            "status": "fail",
            "data": {
                "message": "Unauthorized. The authorization token supplied"
                        " is invalid"
            }
        })
        unauthorized_response.status_code = 401
        expired_response = jsonify({
            "status": "fail",
            "data": {
                "message": "The authorization token supplied is expired"
            }
        })
        expired_response.status_code = 401

        try:
            # extracts token by removing bearer
            authorization_token = authorization_token.split(' ')[1]

            # decode token
            payload = jwt.decode(authorization_token, 'secret',
                                 options={"verify_signature": False})
        except jwt.ExpiredSignatureError:
            return expired_response
        except jwt.InvalidTokenError:
            return unauthorized_response
        
        # convert payload keys from unicode to string
        payload_keys = [str(key) for key in payload.keys()]
        
        # confirm that payload has required keys
        if not {"id", "stamp"}.issubset(payload_keys):
            return unauthorized_response
        else:
            # instantiate user object
            current_user = CurrentUser(
                    str(payload["id"]), str(payload["stamp"])
                )

            # set current user in flask global variable, g
            g.current_user = current_user

            # now return wrapped function
            return f(*args, **kwargs)
Example #23
0
def decode_auth_token(auth_token):
    return jwt.decode(auth_token,
                      key=container.config['JWT_SECRET'],
                      algorithms=container.config['JWT_ALGORITHM'])
def authenticator(auth):
    try:
        auth = auth[2:-1]
    except TypeError:
        print(auth)
    return jwt.decode(auth, 'secret', algorithms='HS256', verify=False)
Example #25
0
def parse_token(req):

    token = req.headers.get('Authorization').split()[1]
    return jwt.decode(token, SECRET_KEY, algorithms='HS256')