Exemplo n.º 1
0
def registration_view(request):
    if request.method == 'POST':
        res = {}
        data = json.loads(request.body)
        email = data['email'].lower()
        password = data['password']
        if validate_email(email) != None:
            res['error_message'] = 'This email is already in use.'
            res['response'] = 'Error'
            return JsonResponse(res, status=400)
        passValid = validate_password(password)
        if passValid != None:
            res['error_message'] = passValid
            res['response'] = 'Error'
            return JsonResponse(res, status=400)

        serializer = RegistrationSerializer(data=data)

        if serializer.is_valid():
            user = serializer.save()
            token = create_token(user.id)
            return JsonResponse(user.getUserResponse(token), status=201)
        else:
            error = serializer.errors
        return JsonResponse(error, status=400)
Exemplo n.º 2
0
def login(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        user = authenticate(email=data['email'], password=data['password'])
        if user:
            token = create_token(user.id)
            return JsonResponse(user.getUserResponse(token))
        return JsonResponse({'error': 'wrong email or password'}, status=401)
Exemplo n.º 3
0
 def test_jwt(self):
     user = User(id=55, user_name='kulich', email='*****@*****.**')
     secret = 'ZZigIKCHuSNeSHwfU+TAbyNX4nwyMUDRXnv0aZgBlOM'
     token = create_token(user, secret)
     claim = verify_token(token, secret)
     self.assertEqual(user.id, claim['id'])
     self.assertEqual(user.user_name, claim['user_name'])
     self.assertEqual(user.email, claim['email'])
     self.assertTrue(verify_token(token, 'bad secret') is None)
     token2 = create_token(user, secret, -0.5)
     self.assertTrue(verify_token(token2, secret) is None)
     claim = verify_token(token2, secret, validate_expiration=False)
     self.assertEqual(user.id, claim['id'])
     
     token3 = create_refresh_token(user, secret, valid_hours = 24*364)
     claim = verify_token(token3, secret)
     self.assertEqual(user.id, claim['id'])
Exemplo n.º 4
0
    def post(self, request):
        resp = get_result()
        try:
            json_data = request.data
            password = json_data.get("password")
            name = json_data.get("name")
            user = OAUser.objects.filter(deleted=False, name=name).first()
            # 用户不存在或者密码错误
            if not user or not user.validate_pwd(password):
                return JsonResponse(get_result("PasswordOrUsernameError"))
        except Exception as e:
            print(traceback.format_exc())
            return JsonResponse(get_result("ParamsError"))

        # 请求成功
        token = create_token()
        cache.set(token, user.id, 6000)
        oaUserSer = OaUserSerializer(user)
        user_data = oaUserSer.data
        user_data.update({"token": token})
        resp.update({"data": user_data})
        return JsonResponse(resp)
Exemplo n.º 5
0
def convert_source(id):
    token = create_token(current_user, current_app.config['SECRET_KEY'],
                         current_app.config['TOKEN_VALIDITY_HOURS'])
    source_id = int(request.form['source_id'])
    format = request.form['format']
    if IN_UWSGI:
        uwsgi.mule_msg(token + '|' + str(source_id) + '|' + format)
        task_id = ''
    else:
        if not loop.is_running():
            abort(500, 'Event loop is not running')
        client = WAMPClient(token, current_app.config['WAMP_URI'], loop=loop)
        try:
            task_id = client.call_no_wait('convert', source_id, format)
        finally:
            client.close()
        if not task_id:
            abort(500, 'No task id')

    url = url_for('minimal.ebook_detail', id=id)
    flash(Markup('File was send for conversion %s- it\'ll take a while - <a href="%s">reload this page</a> later to view link to converted file' %\
                 ('' if not task_id else 'ref. %s '%task_id, url)))
    return redirect(url)
Exemplo n.º 6
0
def login():
    def check_user(username, pwd):
        user = model.User.query.filter(or_(model.User.user_name == username,  # @UndefinedVariable
                                           model.User.email == username)).one_or_none()  # @UndefinedVariable
        if user and check_pwd(pwd, user.password):
            return user

    username = ""
    if request.method == 'POST':
        if request.mimetype == 'application/json':
            credentials = request.get_json()

            if credentials and (credentials.get('email') or credentials.get('username')) and\
                    credentials.get('password'):
                q = model.User.query
                if 'username' in credentials:
                    q = q.filter(
                        model.User.user_name == credentials['username'])
                else:
                    q = q.filter(model.User.email == credentials['email'])

                try:
                    user = q.one()
                except NoResultFound:
                    return jsonify(error='Invalid Login')
                if not user.is_active:
                    return jsonify(error='Invalid Login')
                if not check_pwd(credentials['password'], user.password):
                    return jsonify(error='Invalid Login')
                resp = jsonify(
                    access_token=create_token(user, SECRET_KEY, TOKEN_VALIDITY_HOURS or 4),
                    refresh_token = create_refresh_token(user, 
                                                         current_app.config['SECRET_KEY2'], 
                                                         current_app.config['TOKEN_REFRESH_HOURS']))
                # resp.headers.extend(cors_headers)
                return resp
            elif credentials and credentials.get('refresh_token'):
                header = request.headers.get('Authorization')
                if not header:
                    abort(400, 'Need authorization header to refresh token')
                m = re.match(r'Bearer\s+(.+)', header, re.IGNORECASE)
                if not m:
                    abort(400, 'Invalid authorization header')
                token = m.group(1)
                claim = verify_token(token,  SECRET_KEY, validate_expiration=False)
                if not claim:
                    abort(400, 'Invalid token')
                    
                user_id = claim['id']
                refresh_claim = verify_token(credentials['refresh_token'], current_app.config['SECRET_KEY2'])
                if not refresh_claim:
                    abort(400, 'Invalid refresh token')
                    
                if not user_id == refresh_claim['id']:
                    abort(400, 'Inconsistent tokens')
                    
                user = model.User.query.get(user_id)
                if not user:
                    return jsonify(error='Invalid Login')
                
                return jsonify(
                    access_token=create_token(user, SECRET_KEY, TOKEN_VALIDITY_HOURS or 4))
                
                
            else:
                logger.info('Failed JSON login with %s', credentials)
                abort(400, 'Provide credentials')
        else:

            user = check_user(
                request.form['username'], request.form['password'])

            if user:
                remember_me = request.form.get('rememberme')
                logger.info('User logged in %s , remember me is %s', user.user_name, remember_me)
                login_user(user, remember=remember_me)
                # request.args.get("next")
                return redirect('/')
            else:
                flash('Invalid user name or password!')

    return render_template('login.html', username=username)
Exemplo n.º 7
0
def login():
    def check_user(username, pwd):
        user = model.User.query.filter(
            or_(
                model.User.user_name == username,  # @UndefinedVariable
                model.User.email ==
                username)).one_or_none()  # @UndefinedVariable
        if user and check_pwd(pwd, user.password):
            return user

    username = ""
    if request.method == 'POST':
        if request.mimetype == 'application/json':
            credentials = request.get_json()

            if credentials and (credentials.get('email') or credentials.get('username')) and\
                    credentials.get('password'):
                q = model.User.query
                if 'username' in credentials:
                    q = q.filter(
                        model.User.user_name == credentials['username'])
                else:
                    q = q.filter(model.User.email == credentials['email'])

                try:
                    user = q.one()
                except NoResultFound:
                    return jsonify(error='Invalid Login')
                if not user.is_active:
                    return jsonify(error='Invalid Login')
                if not check_pwd(credentials['password'], user.password):
                    return jsonify(error='Invalid Login')
                resp = jsonify(access_token=create_token(
                    user, SECRET_KEY, TOKEN_VALIDITY_HOURS or 4),
                               refresh_token=create_refresh_token(
                                   user, current_app.config['SECRET_KEY2'],
                                   current_app.config['TOKEN_REFRESH_HOURS']))
                # resp.headers.extend(cors_headers)
                return resp
            elif credentials and credentials.get('refresh_token'):
                header = request.headers.get('Authorization')
                if not header:
                    abort(400, 'Need authorization header to refresh token')
                m = re.match(r'Bearer\s+(.+)', header, re.IGNORECASE)
                if not m:
                    abort(400, 'Invalid authorization header')
                token = m.group(1)
                claim = verify_token(token,
                                     SECRET_KEY,
                                     validate_expiration=False)
                if not claim:
                    abort(400, 'Invalid token')

                user_id = claim['id']
                refresh_claim = verify_token(credentials['refresh_token'],
                                             current_app.config['SECRET_KEY2'])
                if not refresh_claim:
                    abort(400, 'Invalid refresh token')

                if not user_id == refresh_claim['id']:
                    abort(400, 'Inconsistent tokens')

                user = model.User.query.get(user_id)
                if not user:
                    return jsonify(error='Invalid Login')

                return jsonify(access_token=create_token(
                    user, SECRET_KEY, TOKEN_VALIDITY_HOURS or 4))

            else:
                logger.info('Failed JSON login with %s', credentials)
                abort(400, 'Provide credentials')
        else:

            user = check_user(request.form['username'],
                              request.form['password'])

            if user:
                remember_me = request.form.get('rememberme')
                logger.info('User logged in %s , remember me is %s',
                            user.user_name, remember_me)
                login_user(user, remember=remember_me)
                # request.args.get("next")
                return redirect('/')
            else:
                flash('Invalid user name or password!')

    return render_template('login.html', username=username)