Exemple #1
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')
Exemple #2
0
def cmd_token(update: Update, context: CallbackContext):
    username = update.effective_user.username
    logging.info(f"{username} try to generate token")
    if username in ADMIN_USERNAMES:
        token = gen_token()
        tokens.add(token)
        logging.info(f"token generated by {username}")
        send_msg(update, context, f"one time token generated: `{token}`", md=True)
    else:
        logging.info(f"denied for {username}")
        send_msg(update, context, "permission denied, please contact the bot owner")
Exemple #3
0
    def put(self):
        """
        Update ip and get new token
        :return: {id, json web token}
        """
        json_data, error = get_data(request)
        if not error:
            device_data, error = validate_json_payload(json_data, self.fields)
            device_data['ip'] = request.remote_addr
            if not error:
                error = self._validate_data(
                    mac=device_data['mac'],
                    ip=device_data['ip'],
                    password=device_data['password'],
                    role_name=device_data['role']
                    if 'role' in device_data.keys() else None)
                if not error:
                    device_data['password'] = hash_password(
                        device_data['password'])
                    token = gen_token(
                        {key: device_data[key]
                         for key in self.token_data})
                    try:
                        role = Role.query.filter_by(
                            role_name=device_data['role'] if 'role' in
                            device_data.keys() else 'Limited').first()
                        jetson = Jetson.query.filter_by(
                            mac=device_data['mac']).first()
                        account = Account.query.filter_by(
                            id=jetson.account_id).first()
                        truck = Truck.query.filter_by(
                            jetson_id=jetson.id).first()
                    except:
                        return response(401, 'Jetson device dosen\'t exists')

                    if jetson.ip != device_data['ip']:
                        jetson.ip = device_data['ip'] + '3'
                        error = jetson.save()
                        if error:
                            return response(500, 'Internal error')

                    if role.id != account.role_id:
                        account.role_id = role.id
                    error = account.save()

                    if not error:
                        return response(200,
                                        data={
                                            'id': account.id,
                                            'truck_id': truck.id,
                                            'token': token
                                        })
        return error
Exemple #4
0
    def post(self):
        # @TODO: Implement PiConsulting: Needs to authenticate OAUTH
        json_data, error = get_data(request)
        if not error:
            username = json_data['username']
            user = User.query.filter_by(username=username).first()
            # @TODO: Validate password

            account = Account.query.filter_by(id=user.account_id).first()
            json_data['password'] = hash_password(json_data['password'])
            token = gen_token(json_data)

        return response(200, data={'token': token})
Exemple #5
0
    def post(self):
        username = self.get_argument("name", None)
        passwd = self.get_argument("passwd", None)
        platform = self.get_argument("platform", None)
        is_remember = self.get_argument("is_remember", None)
        if not username or not passwd:
            self.json_response({"message": "user name or password is empty"}, status=400)
        user = User(self.db).get_by_username(username)
        if not user:
            self.json_response({"message": "cannot find the user"}, status=404)
        passwd = md5(passwd).hexdigest()
        if passwd != user.get("password"):
            self.json_response({"message": "password is wrong"}, status=403)
        new_token = gen_token(user.get("id"))
        Token(self.db).save(user.get("id"), new_token, platform)
        if not is_remember:
            self.set_secure_cookie("token", new_token)
        else:
            self.set_secure_cookie("token", new_token, expires_days=14)

        self.write("login success")
        self.finish()
Exemple #6
0
    def post(self):
        errors = []
        next_url = self.get_argument('next', '/summary')
        username = self.get_argument('username', '')
        password = self.get_argument('password', '')
        if not username:
            errors.append("请输入用户名!")
        if not password:
            errors.append("请输入用户密码!")
        if errors:
            return self.render('account/login.html', errors=errors)

        username = tornado.escape.xhtml_escape(username)
        ac = accounts.get_info_by_username(username)
        if ac and utils.validate_pwd(ac['pwd'], password, ac['salt']):
            token = utils.gen_token()
            self.set_secure_cookie('token', token, expires_days=1)
            self.redis.setex(token, ac['id'], 86400)
            self.redirect(next_url)
        else:
            errors.append("用户名或密码错误!")
            return self.render("account/login.html", errors=errors)
Exemple #7
0
    def post(self):
        errors = []
        username = self.get_argument('username', '')
        password = self.get_argument('password', '')

        if not username:
            errors.append(u"请输入用户名")
        if not password:
            errors.append(u"请输入用户密码!")
        if errors:
            return self.render('account/login.html', errors=errors)

        username = tornado.escape.xhtml_escape(username)
        account = accounts.get_info_by_username(username)
        if account and utils.validate_pwd(account['pwd'], password, account['salt']):
            token = utils.gen_token()
            self.set_secure_cookie('token', token, expires_days=2)
            self.redis.setex(token, account['id'], 86400)
            self.redirect('home')
        else:
            errors.append(u"用户名或密码错误")
            rerturn render("account/login.html", errors=errors)
Exemple #8
0
    def post(self):
        """
        Register a new jetson device
        :return: {id, json web token}
        """
        json_data, error = get_data(request)
        if not error:
            device_data, error = validate_json_payload(json_data, self.fields)
            device_data[
                'ip'] = request.remote_addr  # TODO: que pasa si el ip ya existe en otro jetson?
            if not error:
                error = self._validate_data(
                    mac=device_data['mac'],
                    ip=device_data['ip'],
                    password=device_data['password'],
                    name=device_data['name'],
                    role_name=device_data['role']
                    if 'role' in device_data.keys() else None)
                if not error:
                    device_data['password'] = hash_password(
                        device_data['password'])
                    token = gen_token(
                        {key: device_data[key]
                         for key in self.token_data})

                    try:
                        role = Role.query.filter_by(
                            role_name=device_data['role'] if 'role' in
                            device_data.keys() else 'Limited').first()
                        account_data = self.account_schema.load({
                            'password':
                            device_data['password'],
                            'role_id':
                            role.id
                        })
                        jetson_data = self.jetson_schema.load({
                            'ip':
                            device_data['ip'],
                            'mac':
                            device_data['mac']
                        })
                        truck_data = self.truck_schema.load(
                            {'name': device_data['name']})

                    except marshmallow.exceptions.ValidationError as errors:
                        return response(400, str(errors))

                    account = Account(**account_data)

                    error = account.save()
                    if not error:
                        jetson = Jetson(**jetson_data)
                        jetson.account_id = account.id
                        error = jetson.save()
                        if not error:
                            truck = Truck(**truck_data, account_id=account.id)
                            truck.jetson_id = jetson.id
                            error = truck.save()
                            if not error:
                                return response(200,
                                                data={
                                                    'id': account.id,
                                                    'truck_id': truck.id,
                                                    'token': token
                                                })
        return error
Exemple #9
0
    def put(self):
        """
        Update data to new user and return new token
        :return: {id, json web token}
        """
        json_data, error = get_data(request)
        if not error:
            data, error = validate_json_payload(json_data,
                                                [('token', True),
                                                 ('new_user', True)])
            if not error:

                curr_user, error = self.get_usertoken_data(data['token'])

                # curr_user = token_data['username']

                _, error = validate_json_payload(
                    data['new_user'],
                    [('username', True)] + [(field, False)
                                            for field, _ in self.fields[1:]])
                if not error:
                    update_user = data['new_user']
                    del data

                    if self.validate_permission(curr_user, 'update_new_user'):
                        if self._validate_user(update_user['username']):
                            error = self._validate_data(
                                password=update_user['password']
                                if 'password' in update_user.keys() else None,
                                email=update_user['email']
                                if 'email' in update_user.keys() else None,
                                role_name=update_user['role']
                                if 'role' in update_user.keys() else None)

                            if not error:
                                if 'password' in update_user.keys():
                                    update_user['password'] = hash_password(
                                        update_user['password'])

                                token = gen_token({
                                    key: update_user[key]
                                    for key in self.token_data
                                })

                                user = User.query.filter_by(
                                    username=update_user['username']).first()
                                account = Account.query.filter_by(
                                    id=user.account_id).first()

                                if 'email' in update_user.keys():
                                    user.email = update_user['email']
                                user.last_update = dt.now().strftime(
                                    '%Y-%m-%d %H:%M:%S')
                                error = user.save()
                                if not error:
                                    if 'role' in update_user.keys():
                                        role = Role.query.filter_by(
                                            role_name=update_user['role']
                                        ).first()
                                        account.role_id = role.id
                                    if 'password' in update_user.keys():
                                        account.password = update_user[
                                            'password']
                                    error = account.save()
                                    if not error:
                                        return response(200,
                                                        data={
                                                            'id': account.id,
                                                            'token': token
                                                        })
                    else:
                        return response(400,
                                        'Current user don\'t has permission')
        return error
Exemple #10
0
    def post(self):
        """
        Register a new user if curr_user has permission
        :param requests: {token: curr_user_token    , new_user:{username, password, email, role}}
        :return: {id, json web token}
        """
        json_data, error = get_data(request)
        if not error:
            data, error = validate_json_payload(json_data,
                                                [('token', True),
                                                 ('new_user', True)])
            if not error:
                token_data, error = self.get_usertoken_data(data['token'])
                curr_user = token_data['username']

                _, error = validate_json_payload(data['new_user'], self.fields)
                if not error:
                    new_user = data['new_user']
                    del token_data, data

                    if self.validate_permission(curr_user, 'create_new_user'):
                        error = self._validate_data(
                            username=new_user['username'],
                            password=new_user['password'],
                            email=new_user['email'],
                            role_name=new_user['role'])
                        if not error:
                            new_user['password'] = hash_password(
                                new_user['password'])
                            token = gen_token({
                                key: new_user[key]
                                for key in self.token_data
                            })

                            try:
                                role = Role.query.filter_by(
                                    role_name=new_user['role']).first()
                                account_data = self.account_schema.load({
                                    'password':
                                    new_user['password'],
                                    'role_id':
                                    role.id
                                })
                                user_data = self.user_schema.load({
                                    'username':
                                    new_user['username'],
                                    'email':
                                    new_user['email']
                                })
                            except marshmallow.exceptions.ValidationError as errors:
                                return response(400, str(errors))

                            new_account = Account(**account_data)
                            new_user = User(**user_data)

                            error = new_account.save()
                            if not error:
                                new_user.account_id = new_account.id
                                error = new_user.save()
                                if not error:
                                    return response(200,
                                                    data={
                                                        'id': new_user.id,
                                                        'token': token
                                                    })
                    else:
                        return response(400,
                                        'Current user don\'t has permission')
        return error