Exemple #1
0
def access_token_view():
    grant_type = request.form.get('grant_type')
    code = request.form.get('code')
    if grant_type.lower() != 'authorization_code' or not code:
        return send_error(request, 400)

    app = extract_client(request, OAUTH2_APPS)
    grant = mongo.db.OAuth2Code.find({
        'app': app['client_id'],
        'token': code,
        'expires': {
            '$gt': datetime.now()
        }
    })
    if grant.count() == 0:
        return send_error(request, 404)

    grant = cursor_to_list(grant)[0]
    token = {
        'expires': datetime.now() + timedelta(seconds=36000),
        'access_token': generate_token(),
        'refresh_token': generate_token(),
        'token_type': 'Bearer',
        'user': grant['user'],
    }
    mongo.db.OAuth2Access.insert(token)
    mongo.db.OAuth2Code.delete_one({'token': code, 'app': app['client_id']})
    token['expires'] = 36000
    return send_response(request, token)
Exemple #2
0
 def token(self):
     """ Generate an auth token for number """
     parser = argparse.ArgumentParser(description=generate_token.__doc__,
                                      prog=f'{self.parser.prog} token')
     parser.add_argument(
         'number', help='Number in international format e.g. +353861230000')
     args = vars(parser.parse_args(argv[2:]))
     args['headers'] = self.bot.headers
     generate_token(**args)
Exemple #3
0
    def post(self):
        json_data = request.get_json()
        data, errors = user_schema.load(data=json_data)
        if errors:
            return {
                'message': 'Validation errors',
                'errors': errors
            }, HTTPStatus.BAD_REQUEST

        if User.get_by_username(data.get('username')):
            return {'message': 'username already used'}, HTTPStatus.BAD_REQUEST

        if User.get_by_email(data.get('email')):
            return {'message': 'email already used'}, HTTPStatus.BAD_REQUEST

        user = User(**data)
        user.save()

        token = generate_token(user.email, salt='activate')

        subject = 'Please confirm your registration.'

        link = url_for('useractivateresource', token=token, _external=True)

        text = 'Hi, Thanks for using Gym-Planner! Please confirm your registration by clicking on the link: {}'.format(
            link)

        mailgun.send_email(to=user.email, subject=subject, text=text)

        return user_schema.dump(user).data, HTTPStatus.CREATED
Exemple #4
0
    def post(self):

        json_data = request.get_json()

        current_user = get_jwt_identity()

        data, errors = user_schema.load(data=json_data)

        if errors:
            return {
                'message': 'Validation errors',
                'errors': errors
            }, HTTPStatus.BAD_REQUEST

        user = User(**data)
        user.save()
        token = generate_token(user.email, salt='activate')
        subject = 'Please Confirm Your Registration.'
        link = url_for('useractivateresource', token=token, _external=True)
        mailgun.send_email(to=user.email,
                           subject=subject,
                           html=render_template('email/confirmation.html',
                                                link=link))

        return user_schema.dump(user).data, HTTPStatus.CREATED
Exemple #5
0
    def post(self):
        json_data = request.get_json()
        data, errors = user_schema.load(data=json_data)

        if errors:
            return {
                'message': 'Validation Errors',
                'Errors': errors
            }, HTTPStatus.BAD_REQUEST

        if User.get_by_username(data.get('username')):
            return {'message': 'username already used'}, HTTPStatus.BAD_REQUEST

        if User.get_by_email(data.get('email')):
            return {'message': 'email aready used'}, HTTPStatus.BAD_REQUEST

        user = User(**data)
        user.save()
        token = generate_token(
            user.email,
            salt='activate')  # Token is used to activate the account

        subject = 'Please confirm your registration'
        link = url_for(
            'useractivateresource', token=token,
            _external=True)  # Convert the default relative URL to absolute
        text = f'Hi,Thanks for using The Daily Cook! Please confirm your registration by clicking on the link:{link}'

        mailgun.send_email(to=user.email,
                           subject=subject,
                           text=text,
                           html=render_template('email/confirmation.html',
                                                link=link))

        return user_schema.dump(user).data, HTTPStatus.CREATED
    def post(self):
        '''do the login :)'''
        email = self.request.data.get('email')
        password = self.request.data.get('password')

        user = yield from db.users.find_one({
            'email': email
        })

        if user:
            password_hash = yield from utils.get_password_hash(
                user['salt'],
                password.encode()
            )
            if user['password'] == password_hash:
                user['last_login'] = datetime.datetime.now()
                yield from db.users.save(user)

                user['token'] = yield from utils.generate_token(user)
                yield from serializers.user(user)
                self.response.set_content(user)
            else:
                self.invalid_response()
        else:
            self.invalid_response()
        yield from self.response.close()
Exemple #7
0
    def __init__(self):
        """
        微信Web
        @param: data_ticket 微信上传资源所需凭证
        @param: BaseRequest 调用接口基本凭证
        @param: my 登录用户后的信息
        @param: skey 调用接口基本凭证skey
        @oaran: wxsid 调用接口基本凭证wxsid
        @param: wxuin 调用接口基本凭证wxuin
        @param: pass_ticket query string url 接口所需凭证
        @param: syncKey 微信每次交互,同步key
        """
        self.data_ticket = ''
        self.BaseRequest = ''
        self.My = ''
        self.skey = ''
        self.wxsid = ''
        self.wxuin = ''
        self.pass_ticket = ''
        self.syncKey = ''
    
        self.tip = 1
        self.base_uri = ''
        self.push_uri = ''
        self.redirect_uri = ''
        self.upload_uri = 'https://file.wx.qq.com/cgi-bin/mmwebwx-bin'

        self.ContactList = []

        # 文件流分隔符
        self.boundary = "----WebKitFormBoundary{}".format(utils.generate_token(16))
Exemple #8
0
    def post(self):
        json_data = request.get_json()

        data, errors = user_schema.load(data=json_data)
        if errors:
            return {
                'message': 'Validation errors',
                'errors': errors
            }, HTTPStatus.BAD_REQUEST
        if User.get_by_username(data.get('username')):
            return {
                'message': 'username already taken'
            }, HTTPStatus.BAD_REQUEST
        if User.get_by_email(data.get('email')):
            return {'message': 'email already taken'}, HTTPStatus.BAD_REQUEST

        user = User(**data)
        user.save()
        token = generate_token(user.email, salt='activate')
        subject = 'Please confirm your registration.'
        link = url_for('useractivateresource', token=token, _external=True)
        text = 'Hi, thanks for using SmileCook!'
        mailgun.send_email(to=user.email,
                           subject=subject,
                           text=text,
                           html=render_template('activation.html', link=link))
        return user_schema.dump(user).data, HTTPStatus.CREATED
Exemple #9
0
    def rpc_get_peers(self, sender, args):
        try:
            node_id = args["id"]
            info_hash = args["info_hash"]

            source = Node(node_id, sender[0], sender[1])

            self.welcomeIfNewNode(source)

            values = self.storage.get(info_hash, None)
            if values is not None:
                # We must calculate unique token for sender
                return {
                    "y": "r",
                    "r": {
                        "id": self.sourceNode.id,
                        "token": generate_token(sender[0], sender[1]),
                        "values": encode_values(values)
                    }
                }
            else:
                return self.rpc_find_node(sender, {
                    "id": node_id,
                    "target": info_hash
                })
        except KeyError:
            return self._response_error(203,
                                        "Protocol Error, invalid arguments")
Exemple #10
0
    def __init__(self):
        """
        微信Web
        @param: data_ticket 微信上传资源所需凭证
        @param: BaseRequest 调用接口基本凭证
        @param: my 登录用户后的信息
        @param: skey 调用接口基本凭证skey
        @oaran: wxsid 调用接口基本凭证wxsid
        @param: wxuin 调用接口基本凭证wxuin
        @param: pass_ticket query string url 接口所需凭证
        @param: syncKey 微信每次交互,同步key
        """
        self.data_ticket = ''
        self.BaseRequest = ''
        self.My = ''
        self.skey = ''
        self.wxsid = ''
        self.wxuin = ''
        self.pass_ticket = ''
        self.syncKey = ''

        self.tip = 1
        self.base_uri = ''
        self.push_uri = ''
        self.redirect_uri = ''
        self.upload_uri = 'https://file.wx.qq.com/cgi-bin/mmwebwx-bin'

        self.ContactList = []

        # 文件流分隔符
        self.boundary = "----WebKitFormBoundary{}".format(
            utils.generate_token(16))
Exemple #11
0
def save_account_passwords(conn):
    choice = True
    cur = conn.cursor()

    result = []
    with open(os.path.join(KEY_STORE_DIR, 'secrets.txt'), 'ab') as secret:
        while choice:
            account_name = input('Account name: ')
            password = getpass('Account"s password: '******'wrongfully' encoded by the database encoder (I learnt this the
            #  painful way)
            result.append((account_name, base64.urlsafe_b64encode(token)))
            secret.write(key)
            quiz = input(
                    'Still more? ("Yes" to add more or "No" to quit): '
                    ).lower()

            if quiz in ['yes', 'y', 'no', 'n']:
                if quiz == 'no' or quiz == 'n':
                    logger.info('User chose not to add more accounts')
                    choice = False
            else:
                print('Choices are "Yes" and "No"!')
                logger.warning('Wrong/Unrecognized choice made by user')
                break
    query = '''INSERT INTO vault (account, password) VALUES %s'''
    execute_values(cur, query, result)
    conn.commit()
    cur.close()
Exemple #12
0
    def login(self, request, *args, **kwargs):
        staff_name = request.data.get('staff_name')
        password = request.data.get('password')

        try:
            staff = Staff.objects.get(staff_name=staff_name)

        except Exception as e:
            raise ValidationError(detail="员工不存在")

        if staff.is_delete:
            raise PermissionDenied(detail="员工已离职")

        if not staff.check_password(password):
            raise ValidationError(detail='密码错误')

        token = generate_token()
        cache.set(token, staff.id, timeout=60 * 60 * 24)

        data = {
            'status': 200,
            'msg': '员工登陆成功',
            'token': token,
            'staff': {
                'id': staff.id,
                'staff_name': staff.staff_name,
                'department': staff.department.dp_name,
                'email': staff.email,
                'is_leader': staff.is_leader,
                'is_delete': staff.is_delete
            }
        }
        return Response(data)
Exemple #13
0
 def post(self):
     json_data = request.get_json()
     try:
         data = user_schema.load(data=json_data)
     except ValidationError as error:
         errors = list(error.messages.values())
         return {
             'message': 'Validation errors',
             'errors': [x[0] for x in errors]
         }, HTTPStatus.BAD_REQUEST
     if User.get_by_username(data.get('username')):
         return {'message': 'username already used'}, HTTPStatus.BAD_REQUEST
     if User.get_by_email(data.get('email')):
         return {'message': 'email already used'}, HTTPStatus.BAD_REQUEST
     user = User(**data)
     user.save()
     token = generate_token(user.email, salt='activate')
     subject = 'Please confirm your registration.'
     link = url_for('useractivateresource', token=token, _external=True)
     text = f'Hi, Thanks for using Recipe book! Please confirm your registration by clicking on the link: {link}'
     mailgun.send_email(to=user.email,
                        subject=subject,
                        text=text,
                        html=render_template('email/confirmation.html',
                                             link=link))
     return user_schema.dump(user), HTTPStatus.CREATED
Exemple #14
0
def bestpic(request):
    if request.user.is_anonymous():
        species = utils.random_species_with_multiple_photos()
    else:
        species = utils.random_species_with_multiple_photos(request.user)
    photo1, photo2 = utils.random_photos_for_species(species)
    # We use a token to ensure any given form we serve up can only be
    # submitted once. Used tokens are stored in Redis for 6 minutes. Forms
    # are time-stamped, and a submission from a form older than five minutes
    # (or one with a token within the 6 minute cache) will silently be 
    # discarded.
    token = utils.generate_token()
    context = {
        'species': species,
        'photo1': photo1,
        'photo2': photo2,
        'options': signed.dumps({
            'species': species.pk,
            'contestants': [photo1.pk, photo2.pk],
            'token': token,
            'time': int(time.time()),
        }),
        'request_path': request.path,
    }
    
    if request.method == 'POST':
        context.update(process_submission(request))
    
    return render(request, 'bestpic/index.html', context)
Exemple #15
0
def register_user(username, password):
    conn = sqlite3.connect("database.db")
    cursor = conn.cursor()
    cursor.execute("INSERT INTO users(username, password, user_token)"
                   " VALUES('{}', '{}', '{}')".format(username, password,
                                                      utils.generate_token()))
    conn.commit()
    conn.close()
Exemple #16
0
def before_on_insert_users(items):
    """
     Creates new token for new user. `token` must be unique and not can repeated
     as null.
    """

    for item in items:
        item['token'] = generate_token(item['email'])
Exemple #17
0
def resend_confirm_email():
    if current_user.confirmed:
        return redirect(url_for('main.index'))

    token = generate_token(user=current_user, operation=Operations.CONFIRM)
    send_confirm_email(user=current_user, token=token)
    flash('New email sent, check your inbox.', 'info')
    return redirect(url_for('main.index'))
Exemple #18
0
def register_post():
    form = request.form
    is_success, messages = User.register(form)
    if is_success:
        return redirect(url_for(".login"))
    else:
        token = generate_token()
        return render_template("register.html", token=token, messages=messages)
Exemple #19
0
 def post(self, request):
     data = json.loads(request.body)
     is_valid = authenticate_digi_user(data.get('username', None), data.get('password', None))
     if is_valid:
         token = generate_token()
         return JsonResponse({"token": token})
     else:
         return redirect('%s?next=%s' % ("/api/logout", "/"))
 def register_service(self, request):
     schema = RegisterUserSchema(strict=True)
     try:
         user_data = schema.loads(request.get_data(as_text=True)).data
     except ValueError as e:
         print(e)
     user = self._create_user(user_data)
     token = generate_token(user)
     return token
Exemple #21
0
def login_post():
    form = request.form
    u = User.validate_login(form)
    if u:
        session["user_id"] = u.id
        session.permanent = True
        return redirect(url_for("topic.index"))
    else:
        token = generate_token()
        return render_template("login.html", token=token, messages="用户名或密码错误")
Exemple #22
0
def login_handler():
    args = AuthArgs.from_request(request.get_json())
    user_response = client.find_user_by_email(args.email)
    user = user_response["data"]["user"][0]
    try:
        Password.verify(user.get("password"), args.password)
        rehash_and_save_password_if_needed(user, args.password)
        return JsonWebToken(generate_token(user)).to_json()
    except VerifyMismatchError:
        return {"message": "Invalid credentials"}, 401
Exemple #23
0
def store_content(request_dict: Dict, byte_content: bytes) -> None:
    """
    批量储存响应对象
    :param request_dict: 批量响应对象
    :param byte_content: 字节内容
    :return: None
    """
    path = '/tmp/star_crawler'
    create_folder(path)
    token = None
    name = request_dict["url"].split('&r')[0]
    if request_dict["method"] == POST:
        data = request_dict["data"]
        token = generate_token(name, data)
    elif request_dict["method"] == GET:
        token = generate_token(name)
    content = dumps_content(byte_content)
    with open('{0}/{1}'.format(path, token), mode='wb') as f:
        f.write(content)
Exemple #24
0
 def _send_link_by_email(user):
     token = generate_token(user.email, salt='activate')
     subject = 'Please confirm your registration.'
     link = url_for('useractivateresource', token=token, _external=True)
     html = render_template('mail/confirm' + '.html', link=link, username=user.username)
     text = render_template('mail/confirm' + '.txt', link=link, username=user.username)
     mailgun.send_email(to=user.email,
                        subject=subject,
                        text=text,
                        html=html
                        )
Exemple #25
0
    def create(cls, username, token=None):
        """ Creates and returns a created user based on provided username and token. If token was not provided,
        then it is going to be generated automatically.
        """

        user = cls(username=username)
        if token is None:
            user.token = utils.generate_token()
        else:
            user.token = token
        return user
def build_kwargs(url, json=None, headers=None, file=None):
    return {
        'url': url,
        'json': {} if json is None else json,
        'headers': {
            'api_key': generate_token()
        } if headers is None else headers,
        'files': {
            'file': open(file, 'rb') if file else None
        }
    }
Exemple #27
0
def change_email_request():
    form = ChangeEmailForm()
    if form.validate_on_submit():
        token = generate_token(user=current_user,
                               operation=Operations.CHANGE_EMAIL,
                               new_email=form.email.data.lower())
        send_change_email_email(to=form.email.data,
                                user=current_user,
                                token=token)
        flash('Confirm email sent, check your inbox.', 'info')
        return redirect(url_for('.index', username=current_user.username))
    return render_template('user/settings/change_email.html', form=form)
Exemple #28
0
def register_url():
    access_token = generate_token()
    api_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl"
    headers = {"Authorization": "Bearer %s" % access_token}
    request = {
        "ShortCode": keys.shortcode,
        "ResponseType": "Completed",
        "ConfirmationURL": "Your ConfirmationURL",
        "ValidationURL": "Your ValidationURL"
    }

    response = requests.post(api_url, json=request, headers=headers)
def spawn_bot(socket, level, game):
    game.n_bots += 1
    nickname = f'{level}bot_{game.n_bots}'
    token = generate_token()
    if level == 'dummy':
        return bots.dummy.DummyBot(socket, nickname, token)
    if level == 'easy':
        return bots.easy.EasyBot(socket, nickname, token)
    if level == 'rand':
        return bots.rand.RandBot(socket, nickname, token)
    if level == 'medium':
        return bots.medium.MediumBot(socket, nickname, token)
    return bots.dummy.DummyBot(socket, nickname, token)
Exemple #30
0
def simulate_c2b():
    access_token = generate_token()
    api_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate"
    headers = {"Authorization": "Bearer %s" % access_token}
    request = {
        "ShortCode": keys.shortcode,
        "CommandID": "CustomerPayBillOnline",
        "Amount": "4",
        "Msisdn": keys.test_msisdn,
        "BillRefNumber": "Bill_ref"
    }

    response = requests.post(api_url, json=request, headers=headers)
Exemple #31
0
def register_user(request):
    if request.method == "GET":
        return HttpResponseNotFound("The page you requested does not exist")

    if request.method == "POST":
        try:
            if len(request.POST) != 0:
                name = request.POST['name'].strip()
                username = request.POST['username'].strip()
                password = request.POST['password'].strip()
            else:
                return HttpResponse("Did not find form data in body",
                                    status=500)

            if name is None or username is None or password is None:
                return HttpResponseForbidden(
                    "Please provide a valid name/username/password")

            if len(username) < 4:
                return HttpResponseForbidden(
                    "The username must be atleast 4 characters")

            if len(password) < 6:
                return HttpResponseForbidden(
                    "The password be atleast 6 character")

            if " " in password or " " in username:
                return HttpResponseForbidden(
                    "The username/password cannot contain whitespace")

            user = User.objects.filter(username=username)
            if len(user) != 0:
                return HttpResponseForbidden("This username already exists")

            user = User(username=username,
                        name=name,
                        password=make_password(password),
                        uuid=uuid.uuid4().hex)
            user.save()

            token = generate_token(user.uuid)
            res = json.dumps({"AUTH_TOKEN": token, "NAME": user.name})
            return HttpResponse(res,
                                content_type='application/json',
                                status=200)

        except Exception, e:
            print e
            return HttpResponseForbidden(
                "The request cannot be completed as %s" % e)
Exemple #32
0
    def post(self):
        logout_user()
        if current_user.is_authenticated:
            # TODO
            response = make_response(
                jsonify(code=32, message='already authenticated'))
            return response
        parse = reqparse.RequestParser()
        parse.add_argument('email',
                           type=str,
                           help='邮箱验证不通过',
                           default='*****@*****.**')
        parse.add_argument('password', type=str, help='密码验证不通过')
        args = parse.parse_args()

        email = args.get("email")
        password = args.get("password")
        try:
            user = UserTable.query.filter_by(email=email).first()
        except:
            print("{} User query: {} failure......".format(
                time.strftime("%Y-%m-%d %H:%M:%S"), email))
            response = make_response(jsonify(code=31,
                                             message='user not found'))
            return response
        else:
            print("{} User query: {} success...".format(
                time.strftime("%Y-%m-%d %H:%M:%S"), email))
        finally:
            db.session.close()
        if user and user.varify_password(password):
            login_user(user, remember=True)
            token = generate_token(current_user.uid)
            print('current_user')
            print(current_user)
            response = jsonify(code=0,
                               message='login success',
                               data={
                                   'user': self.serialize_user(user),
                                   'token': token
                               })
            response.set_cookie('token', token)
            return response
        else:
            print('in if')
            print("{} User query: {} failure...".format(
                time.strftime("%Y-%m-%d %H:%M:%S"), email))
            print('user is None or password False')
            response = make_response(jsonify(code=33, message='login fail'))
            return response
Exemple #33
0
def share_link(update: Update, context: CallbackContext) -> int:
    query = update.callback_query
    query.answer()
    bot = context.bot

    user_data = context.user_data['payment']
    numOfPersons = int(user_data['Number of people'])

    payloads = []
    i = 0
    if (context.user_data['payment']['equal']['bool'] == True):
        text = f"{facts_to_str(user_data)}"
    else:
        text = f"{multi_users_to_str(user_data)}"

    event_id = add_event(context.user_data['user_id'], user_data['Title'])
    while i < numOfPersons:
        payloads.append(generate_token())
        # TODO: link can only share to groups not individuals
        url = helpers.create_deep_linked_url(bot.username, str(payloads[i]))
        if (context.user_data['payment']['equal']['bool'] == True):
            amount = int(context.user_data['payment']['Amount'])
            add_payment(context.user_data['user_id'], amount / numOfPersons,
                        event_id, str(payloads[i]), user_data['Title'])
            text += (
                f"Share the payment information to your friend {i+1}: [▶️ CLICK HERE]({url}). \n"
            )
        else:
            amount = context.user_data['payment']['Amount'][i + 1]['amount']
            add_payment(context.user_data['user_id'], amount, event_id,
                        str(payloads[i]), user_data['Title'])
            text += (
                f"Share the payment information to *{context.user_data['payment']['Amount'][i+1]['name']}* : [▶️ CLICK HERE]({url}). \n"
            )
        i += 1

    keyboard = [[InlineKeyboardButton(BACK, callback_data=str("start"))]]
    reply_markup = InlineKeyboardMarkup(keyboard)

    # clear payment
    context.user_data['payment'] = {}
    # create_deep_linked_url(bot_username, payload=None, group=False)
    # the link will start the bot with /start, cant start with other command
    # url = helpers.create_deep_linked_url(bot.username, CHECK_THIS_OUT, group=True)
    query.edit_message_text(text=text,
                            parse_mode='Markdown',
                            disable_web_page_preview=True,
                            reply_markup=reply_markup)

    return START_OVER
Exemple #34
0
    def post(self):
        json_data = request.get_json()

        data, errors = user_schema.load(data=json_data)

        if errors:
            return {'message': 'Validation errors', 'errors': errors}, HTTPStatus.BAD_REQUEST

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

        non_hash_password = json_data.get('password')

        if User.get_by_username(data.get('username')):
            return {'message': 'username already used'}, HTTPStatus.BAD_REQUEST

        if User.get_by_email(data.get('email')):
            return {'message': 'email already used'}, HTTPStatus.BAD_REQUEST

        # password = hash_password(non_hash_password)

        # user = User(
        #     username=username,
        #     email=email,
        #     password=password
        # )

        user = User(**data)

        user.save()

        token = generate_token(user.email, salt='activate')
        subject = 'Please confirm your registration.'

        link = url_for('useractivateresource',
                       token=token,
                       _external=True)

        text = 'Hi, Thanks for using SmileCook! Please confirm your registration by clicking on the link: {}'.format(link)

        mailgun.send_email(to=user.email, subject=subject,text=text)

        # data = {
        #     'id': user.id,
        #     'username': user.username,
        #     'email': user.email
        # }
        # return data, HTTPStatus.CREATED

        return user_schema.dump(user), HTTPStatus.CREATED
Exemple #35
0
def login(request):
    # handle any POST login attempts, authenticate user and render login view
    if request.method == "POST":
        data = json.loads(request.body)
        is_valid = authenticate_digi_user(data.get('username', None), data.get('password', None))
        if is_valid:
            token = generate_token()
            return JsonResponse({"token": token})
        else:
            return JsonResponse({"login_error": settings.LOGIN_ERROR_MSG})


    # redirected to logout view if GET request
    print "not auth'd rendering logout view"
    return redirect('%s?next=%s' % ("/api/logout", "/"))
Exemple #36
0
 def user_login(username, password):
     '''
     用户登录
     '''
     user = User.get_item('name', username)
     if not user:
         return None
     else:
         password_hashed = User.hash_password(password, user.create_time)
     if user.password == password_hashed:
         user.token = utils.generate_token()
         user.save()
         return user
     else:
         return None
def register():
    credentials = request.get_json(force=True)
    email = credentials['email']
    if not validate_email(email):  
        return jsonify({"code": 2, "token": None})
    app_id = credentials.pop('app_id') 
    if db.session.query(UserAccount).filter_by(email=email).first():
        return jsonify({"code": 1, "token": None})
    else:
        if db.session.query(Application).filter_by(id=app_id).first():
            token = generate_token()
            user = UserAccount(**credentials)
            db.session.add(user)
            db.session.commit()
            db.session.add(UserApplication(user_id=user.id, application_id=app_id, token=token))
            db.session.commit()
            return jsonify({"code": 0, "token": token})
        else:
            return jsonify({"code": 2, "token": None})
Exemple #38
0
    def post(self):
        ''' This method is called on HTTP POST'''
        user = self.request.data
        is_valid = yield from self.validate_user(user)

        if is_valid:
            user['salt'] = yield from utils.generate_salt()
            user['last_login'] = user['created'] = datetime.datetime.now()
            user['modified'] = None
            user['password'] = yield from utils.get_password_hash(
                user['salt'], user['password'].encode()
            )
            db.users.insert(user)
            yield from serializers.user(user)

            # Generate the token
            user['token'] = yield from utils.generate_token(user)

            self.response.status_code = 201
            self.response.set_content(user)
            yield from self.response.close()
def login():
    credentials = request.get_json(force=True)
    email = credentials['email']
    app_id = credentials['app_id']
    password = credentials['password']
    user = db.session.query(UserAccount).filter_by(email=email).first()
    if user and user.check_password(password):
        if db.session.query(Application).filter_by(id=app_id).first():
            token = generate_token()
            user_app, created = get_or_create(UserApplication, application_id=app_id, 
                                            user_id=user.id)
            if not created:
                user_app.last_login = datetime.datetime.now()
                user_app.token = token
            else:
                user_app.token = token
                db.session.add(user_app)
            db.session.commit()
            return jsonify({"code": 0, "token": token})
        else:
            return jsonify({"code": 2, "token": None})
    else:
        return jsonify({"code": 2, "token": None})
Exemple #40
0
    def pre_save(self, created):
        super(User, self).pre_save(created)

        if not self.api_key:
            self.api_key = generate_token(40)
Exemple #41
0
    def post(self):
        data, errors = TokenRequestSchema().loads(
            self.request.body.decode('utf-8'))

        if errors:
            self.send_error(400, message='Wrong input parameters',
                            errors=errors)
            return

        provider = USERINFO_ENDPOINTS[data['provider']]
        query_params = {'access_token': data['access_token']}
        query_params.update(provider['additional_params'])
        userinfo_url = url_concat(provider['url'], query_params)
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(userinfo_url, raise_error=False)
        if response.error:
            errors = json_decode(response.body) if response.body else None
            self.send_error(400, message='Authentication server error',
                            errors=errors)
            return
        else:
            logging.info(json_decode(response.body))

        schema = module_member(provider['schema'])()
        userinfo, errors = schema.loads(to_basestring(response.body))

        if errors:
            self.send_error(400, message='Wrong authentication data received',
                            errors=errors)
            return

        account = self.db.execute(
            'SELECT * FROM accounts WHERE provider = ? AND sub = ?',
            (data['provider'], userinfo['sub'], )
        ).fetchone()

        if account:
            user = self.db.execute(
                'SELECT * FROM users WHERE email = ?', (account['email'], )
            ).fetchone()
            if not user:
                self.send_error(500, message='DB error. User not found.')
                return
        else:
            user = {
                'id': str(uuid.uuid4()),
                'email': userinfo['email']
            }
            self.db.execute(
                'INSERT INTO users (id, email) VALUES (:id, :email)', user)

            account = {
                'user_id': user['id'],
                'provider': data['provider']
            }
            account.update(userinfo)
            self.db.execute(
                'INSERT INTO '
                'accounts (user_id, provider, sub, email, email_verified, name, given_name, family_name, profile, picture, gender) '
                'VALUES (:user_id, :provider, :sub, :email, :email_verified, :name, :given_name, :family_name, :profile, :picture, :gender)',
                account
            )
            self.db.commit()

        now = datetime.utcnow()
        token = {
            'id': generate_token(options.token_length),
            'user_id': user['id'],
            'issued': now,
            'expired': now + options.token_expire_time
        }
        self.db.execute(
            'INSERT INTO tokens (id, user_id, issued, expired) '
            'VALUES (:id, :user_id, :issued, :expired)',
            token
        )
        self.db.commit()

        self.finish(TokenResponseSchema().dumps(token).data)