Пример #1
0
    def check_password(self, raw_password):
        """Verify input password with `password_hash`

        Arguments:
            raw_password {String} -- Input password which to be verified

        Returns:
            Boolean -- Verify result
        """
        return argon2.check_password_hash(self.password_hash, raw_password)
Пример #2
0
def login():
    req = request.get_json()
    username = req.get('username')
    password = req.get('password')

    if not username or not password:
        abort(400)

    user = User.query.filter_by(username=username.lower()).first()

    if not user:
        return jsonify({"msg": "Bad username or password"}), 401

    if not argon2.check_password_hash(user.password_hash, password):
        return jsonify({"msg": "Bad username or password"}), 401

    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token), 200
Пример #3
0
 def check_password(self, password):
     """Check if password is correct"""
     return argon2.check_password_hash(self.password, password)
Пример #4
0
 def check_password(self, password):
     return argon2.check_password_hash(self.password_hash, password)
def session_operation():
    # To login and create a session. The server will return the client a sessionID, client should keep this sessionID to do further requests.
    if request.method == 'POST':
        content = None
        try:
            content = flask.request.get_json(force=True,
                                             silent=False,
                                             cache=True)
            email = content.get("email")
            if email == None:
                return flask.jsonify(result='error',
                                     msg='Email field is required.')
            try:
                password = content.get("password").encode("utf-8")
            except Exception:
                return flask.jsonify(result='error',
                                     msg='Password field is required.')
        except BaseException:
            try:
                email = flask.request.values['email']
                password = flask.request.values['password'].encode("utf-8")
            except BaseException:
                return flask.jsonify(result='error', msg="Wrong json format.")
        try:
            user = models.get_user().find({"email": email})
            # print("list")
            if not user or user.count() == 0:
                return flask.jsonify(result='error',
                                     msg="Check your email and password.")
            if not argon2.check_password_hash(user[0]["password"], password):
                return flask.jsonify(result='error',
                                     msg="Check your email and password.")
            else:
                doc = user[0]
                email = doc['email']
                password = doc['password']
                time_expire = doc['expireTime']
                max_time_live = 14 * 24 * 3600
                time_now_stamp = time.time()
                time_now = datetime.fromtimestamp(time_now_stamp)
                if time_now > time_expire:  ##session expired
                    print("expired")
                    time_expire = datetime.fromtimestamp(time_now_stamp +
                                                         max_time_live)
                    models.get_user().update(
                        {"email": email},
                        {"$set": {
                            "expireTime": time_expire
                        }})
                    user = models.get_user().find({
                        "email": email,
                        "password": password
                    })
                    time_expire = user[0]['expireTime']
                    L = [
                        email,
                        hashlib.md5(
                            ('%s-%s-%s' % (email, password, str(time_expire))
                             ).encode("utf-8")).hexdigest()
                    ]
                    print("Using:%s-%s-%s" %
                          (email, password, str(time_expire)))
                    print("MD5:%s" % (L[1]))
                    return flask.jsonify(result='succeed',
                                         sessionID='-'.join(L))
                else:  ##session not expired
                    # print("not expired")
                    L = [
                        email,
                        hashlib.md5(
                            ('%s-%s-%s' % (email, password, str(time_expire))
                             ).encode("utf-8")).hexdigest()
                    ]
                    print("Using:%s-%s-%s" %
                          (email, password, str(time_expire)))
                    print("MD5:%s" % (L[1]))
                    return flask.jsonify(result='succeed',
                                         sessionID='-'.join(L))
        except BaseException as e:
            return flask.jsonify(result='error', msg=e.__str__())


# To logout and invalidate this session. Notice: the change of a user's password will immediately terminate that user's current session.
    if request.method == 'DELETE':
        content = None
        try:
            content = flask.request.get_json(force=True,
                                             silent=False,
                                             cache=True)
            sessionID = content.get("sessionID")
            if sessionID == None:
                return flask.jsonify(result='error',
                                     msg='SessionID field is required.')
            print(sessionID)
        except BaseException:
            try:
                sessionID = flask.request.values['sessionID']
                if sessionID == None:
                    return flask.jsonify(result='error',
                                         msg='SessionID field is required.')
            except BaseException:
                return flask.jsonify(result='error', msg="Wrong json format.")
        try:
            if auth_sessionID(sessionID):
                list = sessionID.split("-")
                email = list[0]
                time_now_stamp = time.time()
                time_now = datetime.fromtimestamp(time_now_stamp)
                models.get_user().update({"email": email},
                                         {"$set": {
                                             "expireTime": time_now
                                         }})
                return flask.jsonify(result='succeed')
            else:
                return flask.jsonify(result='Invalid session.')
        except BaseException as e:
            return flask.jsonify(result='error', msg=e.__str__())

    return flask.jsonify(result='error', msg='Method not allowed.')
def user_operation():
    # To register a new user.
    if request.method == 'POST':
        content = None
        try:
            content = flask.request.get_json(force=True,
                                             silent=False,
                                             cache=True)
        except BaseException:
            return flask.jsonify(
                result='error', msg=eval("{'request': \"Wrong json format\"}"))
        if content.get("password") == None:
            password = None
        else:
            if len(content.get("password")) < 8:
                password = content.get("password")
            else:
                # password=hashlib.md5((content.get("password")+'athletehq').encode("utf-8")).hexdigest()
                password = argon2.generate_password_hash(
                    (content.get("password")).encode("utf-8"))
        new_user = User(password=password,
                        email=content.get("email"),
                        rfidTag=content.get("RFID"),
                        role=content.get("role"),
                        expireTime=datetime.utcnow())
        new_info = AthleteInfo(athlete=content.get("email"),
                               genTime=datetime.utcnow())
        try:
            new_user.save()
            new_info.save()
        except ValidationError as e:
            return flask.jsonify(result='error', msg=e.to_dict())
        except NotUniqueError as e2:
            return flask.jsonify(
                result='error',
                msg=eval("{'email': \"Account already exists\"}"))
        return flask.jsonify(result='succeed')

# To query all registered users. -->Only for testing.
    if request.method == 'GET':
        users = User.query_users()
        str = ''
        response = {}
        counter = 0
        for user in users:
            counter += 1
            response[counter] = userToString(user)
        return flask.jsonify(allUsers=response)

# User update his/her account information, including change password, role, and rfidTag
    if request.method == 'PUT':
        content = None
        try:
            content = flask.request.get_json(force=True,
                                             silent=False,
                                             cache=True)

        except BaseException:
            return flask.jsonify(
                result='error', msg=eval("{'request': \"Wrong json format\"}"))
        try:
            email = content.get("email")
            password = content.get("password")
        except Exception:
            return flask.jsonify(
                result='error',
                msg='Request should contain email and password.')
        else:
            user = models.get_user().find({"email": email})
            if user and user.count() != 0 and argon2.check_password_hash(
                    user[0]["password"], password):
                newrfidTag = content.get("newRFID")
                if newrfidTag == None:
                    newrfidTag = user[0]["rfidTag"]
                newPassword = content.get("newPassword")
                if newPassword == None:
                    newPassword = user[0]["password"]
                else:
                    if len(newPassword) < 8:
                        return flask.jsonify(
                            result='error',
                            msg=
                            "Password length must be longer than 8 characters."
                        )
                    else:
                        newPassword = argon2.generate_password_hash(
                            (content.get("newPassword")).encode("utf-8"))
                newRole = content.get("newRole")
                if newRole == None:
                    newRole = ""
                if newRole not in ["", "Not Set", "Coach", "Athlete"]:
                    return flask.jsonify(
                        result="error",
                        msg=
                        "new role must be one of 'Coach', 'Athlete','Not Set'")
                if (newRole == 'Athlete'
                        or 'Not Set') and user[0]["role"] == 'Coach':
                    return flask.jsonify(
                        result='error',
                        msg=
                        'Currently, a Coach is not allowed to change his/her role to an Athlete.'
                    )
                if newRole == '':
                    newRole = "Not Set"
                try:
                    print(newRole)
                    models.get_user().update({"email": email}, {
                        "$set": {
                            "password": newPassword,
                            "role": newRole,
                            "rfidTag": newrfidTag
                        }
                    })
                    print(newPassword)
                    return flask.jsonify(result='succeed')
                except Exception as e:
                    return flask.jsonify(result='error', msg=e.__str__())
            else:
                return flask.jsonify(result="error",
                                     msg="Check your email and password.")


# User delete his/her account, all information and linked relationships will be deleted.
    if request.method == 'DELETE':
        content = None
        try:
            content = flask.request.get_json(force=True,
                                             silent=False,
                                             cache=True)

        except BaseException:
            return flask.jsonify(
                result='error', msg=eval("{'request': \"Wrong json format\"}"))
        try:
            email = content.get("email")
            password = content.get("password")
        except Exception:
            return flask.jsonify(
                result='error',
                msg='Request should contain email and password.')
        else:
            users = models.get_user().find({"email": email})
            if users and users.count() != 0 and argon2.check_password_hash(
                    users[0]["password"], password):
                user = users[0]
                hisCouches = models.get_athleteInfo().find({"athlete": email
                                                            })[0]["coaches"]
                for coach in hisCouches:
                    result = unlink(email, coach)
                    if result == 1: continue
                    else:
                        return flask.jsonify(result='error',
                                             msg='Failed, try it later.')
                coaches = models.get_coach().find({"email": email})
                for coach in coaches:
                    hisAthletes = coach['athletes']
                    for athlete in hisAthletes:
                        result = unlink(email, athlete)
                        if result == 1: continue
                        else:
                            return flask.jsonify(result='error',
                                                 msg='Failed, try it later.')
                try:
                    models.get_athleteInfo().remove({"athlete": email})
                    models.get_coach().remove({"email": email})
                    models.get_user().remove({"email": email})
                except Exception as e:
                    return flask.jsonify(result='error',
                                         msg='Failed, try it later.')
                else:
                    return flask.jsonify(result='succeed')
            else:
                return flask.jsonify(result="error",
                                     msg="Check your email and password.")

    return flask.jsonify(result='error', msg='Method not allowed.')