Example #1
0
    def post(self):
        json_data = request.get_json()

        email = json_data.get('email')

        password = json_data.get('password')

        user = User.get_by_email(email=email)

        # check_password  works is by hashing the password the client passes in and comparing that hash value with
        # the one stored in the database
        if not user or not check_password(password, user.password):
            return {
                'message': 'email or password is incorrect'
            }, HTTPStatus.UNAUTHORIZED

        if user.is_active is False:
            return {
                'message': 'The user account is not activated yet'
            }, HTTPStatus.FORBIDDEN

        access_token = create_access_token(identity=user.id, fresh=True)

        refresh_token = create_refresh_token(identity=user.id)

        return {
            'access_token': access_token,
            'refresh_token': refresh_token
        }, HTTPStatus.OK
Example #2
0
def login():
    user = None
    an_error_has_ocurred = False
    username = request.form.get('username')
    password = request.form.get('password')
    errors = {}

    if not username or not utils.validate_data(username, 'username'):
        errors['username_error'] = 'Incorrect username'
        an_error_has_ocurred = True

    elif not User.exist(username=username):
        errors['username_error'] = 'This user does not exist'
        an_error_has_ocurred = True

    else:
        user = User.get(username=username)

        if not password:
            errors['password_error'] = 'Please, introduce the password'
            an_error_has_ocurred = True

        elif not utils.check_password(password, str(user.hashed_password)):
            errors['password_error'] = 'Wrong password'
            an_error_has_ocurred = True

    if not an_error_has_ocurred:
        response = make_response(redirect('/'))
        response.set_cookie('user-token', utils.gen_secure_cookie(user.id))
        return response

    return render_template('index.html', username=username, **errors)
Example #3
0
    def post(self, request):
        post_data = json.loads(request.body.decode('utf-8'))
        password = post_data['password']
        try:
            data = User.objects.filter(email=post_data['email']).all()
        except:
            pass
        try:
            data = User.objects.filter(username=post_data['username']).all()
        except:
            pass

        if (len(data)):
            if check_password(data[0].password, password.encode()):
                serial_data = UserSerializer(data[0]).data
                return JsonResponse({
                    'code': 200,
                    "status": "Login Successfull !!",
                    "userData": serial_data
                })
            else:
                return JsonResponse({
                    'code': 200,
                    "status": "wrong credential !!",
                    "userData": {}
                })

            # perform login and return response
        return JsonResponse({
            "code": 400,
            "status": "Bad request wrong credential"
        })
Example #4
0
def user_update_profile():
    params = utils.flat_multi(request.form)
    password = params.get("current_password")
    new_password = params.get("new_password")
    new_password_confirm = params.get("new_password_confirm")
    email = params.get("email")

    if new_password != new_password_confirm:
        raise WebException("Passwords do not match.")

    user = get_user(username=session["username"]).first()
    correct = utils.check_password(user.password, password)

    if not correct:
        raise WebException("Incorrect password.")
    if new_password != "":
        user.password = utils.hash_password(new_password)

    if email != user.email:
        if get_user(email=email.lower()).count() > 0:
            raise WebException("This email is taken!")
        user.email = email.lower()
        user.email_verified = False

    current_session = db.session.object_session(user)
    current_session.add(user)
    current_session.commit()
    return {"success": 1, "message": "Profile updated."}
Example #5
0
def route_login():
    data = flask.request.form
    username = data.get('username')
    password = data.get('password')

    queried_password = query_password(username)

    if not username or not password:
        # user name or password not supplied to form
        print("didn't specify user name or password to form")
        flask.abort(401)
    elif queried_password is None:
        # couldn't find user in db
        print("couldn't find user")
        flask.abort(401)
    elif check_password(password.encode(), queried_password) == False:
        # incorrect password
        print("incorrect password")
        flask.abort(401)

    # Return a redirect with
    rep = flask.redirect(_app_route)

    # Here we just store the given username in a cookie.
    # Actual session cookies should be signed or use a JWT token.
    rep.set_cookie('custom-auth-session', username)
    return rep
Example #6
0
def user_update_profile():
	params = utils.flat_multi(request.form)
	password = params.get("current_password")
	new_password = params.get("new_password")
	new_password_confirm = params.get("new_password_confirm")
	email = params.get("email")

	if new_password != new_password_confirm:
		raise WebException("Passwords do not match.")

	user = get_user(username=session["username"]).first()
	correct = utils.check_password(user.password, password)

	if not correct:
		raise WebException("Incorrect password.")
	if new_password != "":
		user.password = utils.hash_password(new_password)

	if email != user.email:
		if get_user(email=email.lower()).count() > 0:
			raise WebException("This email is taken!")
		user.email = email.lower()
		user.email_verified = False

	current_session = db.session.object_session(user)
	current_session.add(user)
	current_session.commit()
	return { "success": 1, "message": "Profile updated." }
Example #7
0
def is_valid_login(email, password):
    print "Validating", email, "... (utils)"
    conn = None
    rows = None
    try:
        conn = psycopg2.connect(conn_str)
        cur = conn.cursor()
        cur.execute(sql_mu)
        rows = cur.fetchall()
        cur.close()
    except psycopg2.DatabaseError as error:
        print(error)
        return False
    finally:
        if conn is not None:
            conn.close()
    for row in rows:
        if row[0].rstrip() == email:
            if utils.check_password(row[1].rstrip(), password):
                print "Valid Login (utils)"
                return row[2].rstrip()  # user_id
            else:
                print "Invalid Login (utils)"
                return False
    print "Invalid Login (utils)"
    return False
Example #8
0
def user_twofactor_verify():
	_user = get_user().first()
	if _user is None:
		raise WebException("User not found.")

	params = utils.flat_multi(request.form)

	pwd = params.get("password")
	if pwd is None:
		raise WebException("Please enter your password.")
	if not utils.check_password(_user.password, pwd):
		raise WebException("Incorrect password.")

	if "token" not in params:
		raise WebException("Invalid token.")
	token = params.get("token")

	if not(_user.verify_totp(int(token))):
		raise WebException("Invalid token. Current server time: " + time.strftime("%Y-%m-%d %H:%M:%S"))
	with app.app_context():
		Users.query.filter_by(uid=_user.uid).update({ "otp_confirmed": True })
		db.session.commit()

	print "CONFIRMED"

	return { "success": 1, "message": "Confirmed!" }
Example #9
0
    def post(self):
        """This method has the logic to receive the email together password of the client and
        generate an authentication token
        """
        json_data = request.get_json()
        email = json_data.get('email')
        password = json_data.get('password')

        # Verify the correctness of the user's credentials
        user = User.get_by_email(email=email)

        if not user or not check_password(password, user.password):
            # Return 401 UNAUTHORIZED, with an email message.
            return {
                'message': 'email or password is incorrect'
            }, HTTPStatus.UNAUTHORIZED

        # User cannot log in to the application before their account is activated
        if user.is_active is False:
            return {
                'message': 'The user account is not activated yet'
            }, HTTPStatus.FORBIDDEN

        # Create an access token with the user id as the identity to the user and pass
        # in the fresh=True parameter to the create_access_token function. We
        # then invoke the create_refresh_token function to generate a refresh token..
        access_token = create_access_token(identity=user.id, fresh=True)
        refresh_token = create_refresh_token(identity=user.id)

        return {
            'access_token': access_token,
            'refresh_token': refresh_token
        }, HTTPStatus.OK
Example #10
0
def login():
    if request.method == 'GET':
        if session.get('user', None) is not None:
            return redirect(url_for('index'))
        return render_template('login.html', page='signin')
    elif request.method == 'POST':
        username = request.form.get('username', None)
        password = request.form.get('password', None)

        if username is None or password is None:
            flash(u'请检查输入是否为空', 'danger')
            return redirect(url_for('login'))

        user = User.query.filter_by(username=username).first()
        if user is None:
            flash(u'该用户不存在', 'danger')
            return redirect(url_for('login'))

        if not utils.check_password(user.password, password):
            flash(u'密码错误', 'danger')
            return redirect(url_for('login'))

        session['user'] = {
            'username': user.username,
            'nickname': user.nickname
        }
        return redirect(url_for('index'))
Example #11
0
def user_twofactor_verify():
    _user = get_user().first()
    if _user is None:
        raise WebException("User not found.")

    params = utils.flat_multi(request.form)

    pwd = params.get("password")
    if pwd is None:
        raise WebException("Please enter your password.")
    if not utils.check_password(_user.password, pwd):
        raise WebException("Incorrect password.")

    if "token" not in params:
        raise WebException("Invalid token.")
    token = params.get("token")

    if not (_user.verify_totp(int(token))):
        raise WebException("Invalid token. Current server time: " +
                           time.strftime("%Y-%m-%d %H:%M:%S"))
    with app.app_context():
        Users.query.filter_by(uid=_user.uid).update({"otp_confirmed": True})
        db.session.commit()

    print "CONFIRMED"

    return {"success": 1, "message": "Confirmed!"}
Example #12
0
    def post(self):

        json_data = request.get_json()

        email = json_data.get('email')
        password = json_data.get('password')

        user = User.get_by_email(email=email)

        if not user or not check_password(password, user.password):
            return {
                'message': 'username or password is incorrect'
            }, HTTPStatus.UNAUTHORIZED

        if user.is_active is False:
            return {
                'message': 'The user account is not activated yet'
            }, HTTPStatus.FORBIDDEN

        access_token = create_access_token(identity=user.id, fresh=True)
        refresh_token = create_refresh_token(identity=user.id)

        return {
            'access_token': access_token,
            'refresh_token': refresh_token
        }, HTTPStatus.OK
Example #13
0
 def post(self):
     json_data = request.get_json()
     email = json_data.get("email")
     password = json_data.get("password")
     user = User.get_by_email(email=email)
     if not user or not check_password(password, user.password):
         return (
             {
                 "message": "email or password are incorrect"
             },
             HTTPStatus.UNAUTHORIZED,
         )
     if user.is_active is False:
         return (
             {
                 "message": "The user account is not activated yet"
             },
             HTTPStatus.FORBIDDEN,
         )
     access_token = create_access_token(identity=user.id, fresh=True)
     refresh_token = create_refresh_token(identity=user.id)
     return (
         {
             "access_token": access_token,
             "refresh_token": refresh_token
         },
         HTTPStatus.OK,
     )
Example #14
0
def register():
  """
  Attempts to register the user with the given account information.
  """
  name = request.form['name']
  email = request.form['email']
  password = request.form['password']
  repassword = request.form['repassword']
  name_error = check_name(name)
  if name_error != None:
    # malformed name
    return jsonify({'type': 'error', 'error': name_error})
  email_error = check_email(email)
  if email_error != None:
    # malformed e-mail
    return jsonify({'type': 'error', 'error': email_error})
  password_error = check_password(password, repassword)
  if password_error != None:
    # malformed password
    return jsonify({'type': 'error', 'error': password_error})
  user_exists = db.user_exists(email)
  if user_exists:
    # user with this e-mail already exists
    error = 'An account with this e-mail address already exists!'
    return jsonify({'type': 'error', 'error': error})
  user = db.make_user(name, email, password)
  flash('Welcome to Bookmark+, %s!' % user.name)
  session['user_id'] = unicode(user._id)
  return jsonify({'type': 'success', 'url': url_for('home')})
Example #15
0
 def __call__(self, form, field):
     length = field.data and len(field.data) or 0
     if length == 0:
         pass
     elif check_password(field.data):
         pass
     else:
         raise ValidationError(self.message)
Example #16
0
def delete_user(cursor, username, password):
    user = User.load_user_by_username(cursor, username)
    if not user:
        print('User does not exist!')
    elif check_password(password, user.hashed_password):
        user.delete(cursor)
        print('User has been deleted!')
    else:
        print('Provided password is incorrect!')
Example #17
0
def login():
    user, logged_in = get_user()
    if fsk.request.method == 'POST':
        if utils.check_password(fsk.request.form['username'], fsk.request.form['password']):
            fsk.session['username'] = fsk.request.form['username']
            fsk.redirect(fsk.url_for("index"))
        else:
            error = True

    return fsk.render_template("login.html", error=error)
Example #18
0
def change_password(
        old_password: str = Form(...), new_password: str = Form(...),
        user: User = Depends(require_user), db: Session = Depends(get_db)
):
    db_user = get_user_by_name(db, user.name)
    check = check_password(old_password, db_user.password_hash, db_user.password_salt)
    if check:
        change_user_password(db, user.id, new_password)
        return Response(status_code=status.HTTP_204_NO_CONTENT)
    else:
        raise HTTPException(status_code=400, detail='Wrong password')
Example #19
0
    def post(self):
        json_data = request.get_json()
        email = json_data.get('email')
        password = json_data.get('password')
        user = User.get_by_email(email=email)
        if not user or not check_password(password, user.password):
            return {'message': 'email or password is incorrect'}, \
                HTTPStatus.UNAUTHORIZED

        access_token = create_access_token(identity=user.id)
        return {'access_token': access_token}, HTTPStatus.OK
Example #20
0
 def get(self):
     parser = reqparse.RequestParser()
     parser.add_argument('login', type=str, required=True)
     parser.add_argument('password', type=str, required=True)
     args = parser.parse_args()
     check_res = utils.check_password(args['login'], args['password'])
     if check_res:
         token_res = utils.gen_token(args['login'])
         return token_res
     else:
         abort(401, ok=False, error='invalid login/password')
Example #21
0
def check_login(username, password):
    user_data = db.select(USERS, where='username="******"' % clean_input(username))
    try:
        user_data = user_data[0]
        encode = user_data.password
        user_id = user_data.id
    except IndexError:
        return False, user_pass_not_match
    if not check_password(encode=encode, raw_password=password):
        return False, user_already_exist
    else:
        return True, user_id
Example #22
0
def login_proceed():
    username = request.form.get('username')
    user = login_models.User.query.filter_by(username=username).first()
    if user is None:
        flash('You provided invalid credentials')
        return redirect(url_for('login_view.login'))
    password = request.form.get('password', '')
    if not utils.check_password(password, user.password):
        flash('You provided invalid credentials')
        return redirect(url_for('login_view.login'))
    session['user_id'] = user.id
    return redirect(url_for('index'))
Example #23
0
def request_token(form: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    if not user_exists(db, form.username):
        raise HTTPException(status_code=400, detail='User does not exist')
    user = get_user_by_name(db, form.username)
    check = check_password(form.password, user.password_hash, user.password_salt)
    if check:
        token = set_user_token(db, form.username)
        return {
            'access_token': token,
            'token_type': 'bearer'
        }
    else:
        raise HTTPException(status_code=400, detail='Wrong password')
Example #24
0
def password_edit(cursor, username, password, new_pass):
    user = User.load_user_by_username(cursor, username)
    if not user:
        print('User does not exist!')
    elif check_password(password, user.hashed_password):
        if len(new_pass) >= 8:
            user.hashed_password = new_pass
            user.save_to_db(cursor)
            print('Password has been changed!')
        else:
            print('Provided password is too short, please try again!')
    else:
        print('Provided password is incorrect!')
    def post(self):
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')

        user = User.get_user_by_username(username)

        if not user or not check_password(password, user.password):
            return {
                'message': 'Wrong username or password.'
            }, HTTPStatus.UNAUTHORIZED

        access_token = create_access_token(identity=user.id)
        return {'token': access_token}, HTTPStatus.OK
Example #26
0
    def post(self):

        # 1. 클라이언트로부터 이메일과 비밀번호를 받아온다.
        data = request.get_json()
        if 'email' not in data or 'password' not in data:
            return {'err_code': 1}, HTTPStatus.BAD_REQUEST

        # 2. 이메일 벨리데이션 체크
        try:
            validate_email(data['email'])

        except EmailNotValidError as e:
            print(str(e))
            return {'err_code': 2}, HTTPStatus.BAD_REQUEST

        # 3. 비밀번호가 맞는지 체크하기 위해서 데이터 베이스에서 위의 이메일로
        #    유저 정보를 가져온다. (select)
        connection = get_mysql_connection()
        cursor = connection.cursor(dictionary=True)
        query = """select id, password from yhdb.movie_user
                    where email = %s;"""

        param = (data['email'], )

        cursor.execute(query, param)
        records = cursor.fetchall()
        print(records)

        # 3-1. 회원가입이 안된 이메일로 요청했을때는, record에 데이터가 없으니까
        #      클라이언트에게 응답한다.
        if len(records) == 0:
            return {'err_code': 3}, HTTPStatus.BAD_REQUEST

        # 4. 위에서 가져온 디비에 저장되어있는 비밀번호와, 클라이언트로부터
        #    받은 비밀번호를 암호화 한것과 비교한다.
        password = data['password']
        hashed = records[0]['password']
        ret = check_password(password, hashed)

        # 5. 같으면 클라이언트에 200 리턴
        if ret is True:

            user_id = records[0]['id']
            access_token = create_access_token(identity=user_id)

            return {'token': access_token}, HTTPStatus.OK

        # 6. 다르면, 에러 리턴
        else:
            return {'err_code': 4}, HTTPStatus.BAD_REQUEST
Example #27
0
def login():
    team = request.form["team"]
    password = request.form["password"]
    stored_team_password = teamdb.get_team_password(team)
    if utils.check_password(stored_team_password, password):
        session["tid"] = team
        session["logged_in"] = True
        if teamdb.is_admin(team):
            session["admin"] = True
            logger.log("logins", logger.WARNING, "%s logged as admin" % team)
        else:
            logger.log("logins", logger.INFO, "%s logged in" % team)
        return {"success": 1, "message": "Success!"}
    else:
        return {"success": 0, "message": "Invalid credentials"}
Example #28
0
def check_credentials(email, password):
    records = db.query(
        'SELECT hashed_password, salt '
        'FROM example_users '
        'WHERE email=$email ',
        vars={'email': email})
    if len(records) > 0:
        record = records[0]
        return check_password(
            record['hashed_password'],
            password,
            record['salt'],
        )
    else:
        return False
Example #29
0
    def post(self):

        json_data = request.get_json()

        email = json_data.get('email')
        password = json_data.get('password')

        admin = Admin.get_by_email(email=email)

        if not admin or not check_password(password, admin.password):
            return {'message': 'username or password is incorrect'}, HTTPStatus.UNAUTHORIZED

        access_token = create_access_token(identity=admin.id, fresh=True)
        refresh_token = create_refresh_token(identity=admin.id)

        return {'access_token': access_token, 'refresh_token': refresh_token}, HTTPStatus.OK
Example #30
0
 def post(self):
     user_username = self.request.get("username")
     user_password = self.request.get("password")
     user_verify = self.request.get("verify")
     user_email = self.request.get("email")
     
     uname = user_username
     email = user_email
     
     uname_err = utils.check_username(user_username)
     pw_err=""
     vpw_err=""
     email_err=""
     
     Success= True
     
     if uname_err != "":
         Success= False
         
     if utils.check_password(user_password)==False:
         pw_err="That's not a valid password."
         Success= False
     
     if utils.verify_password(user_password, user_verify)==False:
         vpw_err="Your passwords didn't match."
         Success= False
     if len(email) != 0:
         if utils.check_email(user_email)==False:
             email_err="That's not a valid email."
             Success= False
     
     if Success:
         x = utils.make_pw_hash(uname, user_password)
         saltedPass = x.split("|")[0]
         salt = x.split("|")[1]
         
         if len(email) != 0:
             newUser = User(key_name = uname, username = uname, email=email, password = saltedPass, salt = salt)
         else:
             newUser = User(key_name = uname, username = uname, password = saltedPass, salt = salt)
         newUser.put()
         setUser = "******" + uname
         self.response.headers.add_header('Set-Cookie', setUser.encode())
         self.redirect("/")
     else:
         self.render_signup(uname, email,uname_err, pw_err, vpw_err,email_err)
    def post(self):

        json_data = request.get_json()
        email = json_data.get("email")
        password = json_data.get("password")
        user = User.get_by_email(email=email)
        if not user or not check_password(password, user.password):
            return {
                "message": "Email or password is incorrect"
            }, HTTPStatus.UNAUTHORIZED

        access_token = create_access_token(identity=user.id, fresh=True)
        refresh_token = create_refresh_token(identity=user.id)
        return {
            "access_token": access_token,
            "refresh_token": refresh_token
        }, HTTPStatus.OK
Example #32
0
    def get_user_id(self, login, password):
        """
        Функция проверяет есть ли пользователь с такими логином и паролем в БД.
        В случае если пользователь найден возвращает его идентификатор
        """
        session = self._get_session()
        users = session.query(User).filter(User.login == login).all()
        session.rollback()

        if not users:
            return None

        user = users[0]

        if check_password(password, user.password):
            return user.id
        else:
            return None
Example #33
0
def login_user(username, password, token=None):
	"""
	Logs in the user and creates a login-token with the specified username and password.

	:param username: The username of the user.
	:param password: The password of the user.
	:param token: (Optional) If the user has enabled two-factor authentication, this *must* be passed along with username and password. Otherwise, it may be left as None.
	:returns: Whether the login succeeded or not.
	:rtype: boolean
	"""
	user = get_user(username_lower=username.lower()).first()
	if user is None: return False
	correct = utils.check_password(user.password, password)
	if not correct:
		return False
	if user.tfa_enabled() and not(user.verify_totp(token)):
		return False
	create_login_token(username)
	return True
Example #34
0
def login_user(username, password, token=None):
    """
	Logs in the user and creates a login-token with the specified username and password.

	:param username: The username of the user.
	:param password: The password of the user.
	:param token: (Optional) If the user has enabled two-factor authentication, this *must* be passed along with username and password. Otherwise, it may be left as None.
	:returns: Whether the login succeeded or not.
	:rtype: boolean
	"""
    user = get_user(username_lower=username.lower()).first()
    if user is None: return False
    correct = utils.check_password(user.password, password)
    if not correct:
        return False
    if user.tfa_enabled() and not (user.verify_totp(token)):
        return False
    create_login_token(username)
    return True
Example #35
0
    def post(self):
        form = forms.LoginForm(request.form)
        authorized = False
        error = ''

        username = form.username.data
        password = form.password.data
        remember = form.remember_me.data

        if form.validate():
            user = User.get_user_by_username(username)
            if not user:
                return "Incorrect Username"
            authorized = utils.check_password(password, user)

            if authorized:
                flask_login.login_user(user, remember=remember)
                return "success"

        return "Incorrect Password"
Example #36
0
    def post(self):
        form = forms.LoginForm(request.form)
        authorized = False
        error = ''

        username = form.username.data
        password = form.password.data
        remember = form.remember_me.data

        if form.validate():
            user = User.get_user_by_username(username)
            if not user:
                return "Incorrect Username"
            authorized = utils.check_password(password, user)

            if authorized:
                flask_login.login_user(user, remember=remember)
                return "success"

        return "Incorrect Password"
Example #37
0
 def post(self):
     try:
         data = request.get_json()
         username = data.get('username')
         password = data.get('password')
     except Exception as e:
         raise MyBadRequestException
     try:
         user = User.get_by_username(username=username)
     except Exception as e:
         raise MyInternalServerErrorException
     if user is None or not user or not check_password(
             password, user.password):
         raise MyBadRequestException
     try:
         token, exp = JWTToken.encode(user.username)
         result = {'access_token': token, 'expire_date': exp}
         return {'result': result}, HTTPStatus.CREATED
     except Exception as e:
         raise MyInternalServerErrorException
Example #38
0
    def post(self):
        json_data = request.get_json()
        teacher_username = json_data.get('teacher_username')
        teacher_password = json_data.get('teacher_password')

        teacher = Teacher.get_by_teacher_username(
            teacher_username=teacher_username)

        if not teacher or not check_password(teacher_password,
                                             teacher.teacher_password):
            return {
                'message': 'username or password is incorrect'
            }, HTTPStatus.UNAUTHORIZED

        teacher_access_token = create_access_token(identity=teacher.teacher_id,
                                                   fresh=True)
        teacher_refresh_token = create_refresh_token(
            identity=teacher.teacher_id)
        return {
            'teacher_access_token': teacher_access_token,
            'teacher_refresh_token': teacher_refresh_token
        }, HTTPStatus.OK
Example #39
0
    def post(self):
        json_data = request.get_json()
        student_username = json_data.get('student_username')
        student_password = json_data.get('student_password')

        student = Student.get_by_student_username(
            student_username=student_username)

        if not student or not check_password(student_password,
                                             student.student_password):
            return {
                'message': 'username or password is incorrect'
            }, HTTPStatus.UNAUTHORIZED

        student_access_token = create_access_token(identity=student.student_id,
                                                   fresh=True)
        student_refresh_token = create_refresh_token(
            identity=student.student_id)
        return {
            'student_access_token': student_access_token,
            'student_refresh_token': student_refresh_token
        }, HTTPStatus.OK
Example #40
0
    async def m_login(self, data):
        global objects

        antispam(self.getip(), "login", 40)

        try:
            obj = await objects.get(UserModel, username=data['username'])
            if check_password(obj.password, data['password']):
                self.session = self.create_session(obj, data['username'],
                                                   self.request.remote_ip)
                self.send_data({"key": "form_login", "success": True})
                self.send_session_info()
            else:
                self.send_data({
                    "key": "form_login",
                    "errors": ["Incorrect password!"]
                })
        except UserModel.DoesNotExist:
            self.send_data({
                "key": "form_login",
                "errors": ["Incorrect username!"]
            })
Example #41
0
def login():
    if request.method == 'GET':
        if session.get('user', None) is not None:
            return redirect(url_for('index'))
        return render_template('login.html', page='signin')
    elif request.method == 'POST':
        username = request.form.get('username', None)
        password = request.form.get('password', None)

        if username is None or password is None:
            flash(u'请检查输入是否为空', 'danger')
            return redirect(url_for('login'))

        user = User.query.filter_by(username=username).first()
        if user is None:
            flash(u'该用户不存在', 'danger')
            return redirect(url_for('login'))

        if not utils.check_password(user.password, password):
            flash(u'密码错误', 'danger')
            return redirect(url_for('login'))

        session['user'] = {'username': user.username, 'nickname': user.nickname}
        return redirect(url_for('index'))
Example #42
0
# -*- coding: utf-8 -*-
# Pedimos password
from utils import check_password
import hashlib

constraints = {
	'min-leng': 10,
	'min-mayus': 1,
	'min-minus': 1,
	'min-special': 1,
	'min-number': 2
}

password = input("Introduce una password :"******"Las password no cumple con los requisitos"
	password = input("Introduce una password :"******"La password introducida fue ", password
print "Este es el hash md5 de tu password ",hashlib.md5(password).digest()

Example #43
0
 def test_check_password(self):
   assert check_password('password1', 'password2') is not None
   assert check_password('small', 'small') is not None
   assert check_password('long_enough', 'long_enough') is None
Example #44
0
 def login(cls, username, password):
     user = cls.find_by_name(username)
     if user and check_password(username, password, user.password_hash):
         return user
Example #45
0
 def check_password(self, password):
     """
     Checks the supplied password against the stored password in the database
     returns True if they match, False otherwise
     """
     return check_password(password, self.password_hash, settings.INBOX_SETTINGS['hash_secret'])