Beispiel #1
0
    def post(self):
        data = auth_parser.parse_args()
        access_token_expiration_time = timedelta(days=1)
        refresh_token_expiration_time = timedelta(days=1)

        if models.UserModel.find_by_username(data['username']):
            return {
                'message': 'User {} already exists'.format(data['username'])
            }

        new_user = models.UserModel(username=data['username'],
                                    password=models.UserModel.generate_hash(
                                        data['password']))

        try:
            new_user.save_to_db()
            access_token = create_access_token(
                identity=data['username'],
                expires_delta=access_token_expiration_time)
            refresh_token = create_refresh_token(
                identity=data['username'],
                expires_delta=refresh_token_expiration_time)
            return {
                'message': 'User {} was created'.format(data['username']),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        except:
            return {'message': 'Something went wrong'}, 500
Beispiel #2
0
    def post(self):
        req_json = request.get_json()
        user_email = req_json['email']
        user_pass = req_json['password']

        if models.UserModel.find_by_email(user_email):
            return {'msg': 'User {} already exists'.format(user_email)}, 401

        new_user = models.UserModel(
            email=user_email,
            password=models.UserModel.generate_hash(user_pass))

        try:
            new_user.save_to_db()
            access_token = create_access_token(identity=user_email)
            refresh_token = create_refresh_token(identity=user_email)

            # add the user to the server db
            requests.post('http://server:5000/user', json=req_json)

            return {
                'msg': 'User {} was created'.format(user_email),
                'access_token': access_token,
                'refresh_token': refresh_token
            }
        except Exception as e:
            return {'msg': 'Something went wrong : {}'.format(e)}, 500
    def post(self):
        form = LoginFormGoogle(request.form)

        if form.validate():
            try:
                id_info = id_token.verify_oauth2_token(form.token.data,
                                                       requests.Request(),
                                                       GOOGLE_CLIENT_ID)

                if id_info['iss'] not in ['accounts.google.com',
                                          'https://accounts.google.com']:
                    raise ValueError('Wrong issuer.')

                user = models.UserModel(
                    username=id_info['email'],
                    password=models.UserModel.generate_hash(id_info['sub']),
                    name=id_info['name'],
                    googleid=id_info['sub']
                )
                try:
                    user.save_to_db()
                    a_token = create_access_token(identity=user.username)
                    r_token = create_refresh_token(identity=user.username)
                    return {
                        'access_token': a_token,
                        'refresh_token': r_token,
                        'name': user.name
                    }
                except:
                    raise

            except ValueError:
                return {'message': 'Invalid Google Account'}, 500
        else:
            return {'message': 'Error Register With Google'}, 500
Beispiel #4
0
def create_tables():
    db.create_all()
    if not models.UserModel.find_by_username(os.environ["admin_user"]):
        admin_user = models.UserModel(username=os.environ["admin_user"],
                                      access_level="ADMIN",
                                      password=models.UserModel.generate_hash(
                                          os.environ["admin_password"]))
        admin_user.save_to_db()
Beispiel #5
0
def create_new_user(username, password):
    """Create new user."""
    new_user = models.UserModel(
        username=username, password=models.UserModel.generate_hash(password))
    new_user.save_to_db()
    access_token, refresh_token = create_access_and_refresh_token(
        identity=username)
    return access_token, refresh_token
Beispiel #6
0
class WXUserLoginHandler(APIHandler):
    model = models.UserModel()

    def post(self):
        result = utils.init_response_data()
        try:
            code = self.get_argument("code", "")
            if code == '':
                raise ValueError(u"登录失败")
            js_pub = JsApi_pub()
            js_pub.setCode(code)
            wx_user = js_pub.get_user_info()
            user = self.model.get(wx_user)
            result['data'] = utils.dump(user)
        except Exception as e:
            result = utils.reset_response_data(0, str(e))
        self.finish(result)
Beispiel #7
0
class WXUserHandler(APIHandler):
    model = models.UserModel()

    def get(self, *args, **kwargs):
        self.post(*args, **kwargs)

    def post(self, *args, **kwargs):
        result = utils.init_response_data()
        try:
            user_id = self.get_argument("user_id", "")
            if user_id != "" and user_id != "undefined":
                result['data'] = utils.dump(
                    self.coll.find_one({"_id":
                                        utils.create_objectid(user_id)}))
        except Exception as e:
            result = utils.reset_response_data(0, str(e))
        self.finish(result)
Beispiel #8
0
def add_user():
    name = request.values.get('full_name', None)
    username = request.values.get('username', None)
    regex = re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
    if not regex.match(username):
        return abort(400)
    password = generate_password_hash(request.values.get('password'))

    session = Session()
    new_user = models.UserModel()
    new_user.name = name
    new_user.username = username
    new_user.password = password
    session.add(new_user)
    session.commit()
    login_user(new_user)
    return jsonify({"next": "/"})
Beispiel #9
0
def register():
    if request.method == 'POST':
        # Checks if the username is already in the database.
        if models.UserModel.find_by_username(request.form['uname']):
            resp = make_response(
                render_template('register.html',
                                register_output=
                                'Failure! Username already exists, try again'))
            add_headers(resp)
            return resp, 401

        salt = token_hex(nbytes=16)
        new_user = models.UserModel(
            username=request.form['uname'],
            password=models.UserModel.generate_hash(request.form['pword'],
                                                    salt),
            two_factor=models.UserModel.generate_hash(request.form['2fa'],
                                                      salt),
            pepper=salt)

        try:
            new_user.save_to_db()
            access_token = create_access_token(identity=request.form['uname'])
            refresh_token = create_refresh_token(
                identity=request.form['uname'])
            resp = make_response(
                render_template('register.html',
                                register_output='Account registered Success!'))
            add_headers(resp)
            return resp, 200
        except:
            resp = make_response(
                render_template('register.html',
                                register_output='Something went wrong!'))
            add_headers(resp)
            return resp, 500

    # was GET
    current_user = get_jwt_identity()
    resp = make_response(
        render_template('register.html', current_user=current_user))
    add_headers(resp)
    return resp, 200
    def post(self):
        data = register_parser.parse_args()

        if models.UserModel.find_by_username(data['username']):
            return {'message': '{} exists'.format(data['username'])}

        new_user = models.UserModel(
            username=data['username'],
            password=models.UserModel.generate_hash(data['password']),
            name=data['name']
        )
        try:
            new_user.save_to_db()
            a_token = create_access_token(identity=data['username'])
            r_token = create_refresh_token(identity=data['username'])
            return {
                'access_token': a_token,
                'refresh_token': r_token,
                'name': new_user.name
            }
        except:
            return {'message': 'Register Error'}, 500
Beispiel #11
0
api.add_resource(resources.AllSK8RATs, '/api/SK8RATs')
api.add_resource(resources.SingleSK8RAT, '/api/SK8RATs/<SK8RAT_name>')
api.add_resource(resources.TaskSK8RAT, '/api/tasks/<SK8RAT_name>')
api.add_resource(resources.TaskAllSK8RAT, '/api/tasks')

if not sqlalchemy_utils.database_exists('sqlite:///app.db'):
    db.create_all()

# Check for existing database, then check for existing listener
if sqlalchemy_utils.database_exists('sqlite:///app.db'):
    Listener = models.ListenerModel.query.filter(
        models.ListenerModel.listener_type == "http").first()
    if Listener:
        port = str(Listener.port)
        subprocess.Popen(["./start_listener.sh", port])

# Check that admin user exists
admin_user = models.UserModel.query.filter(
    models.UserModel.username == "sk8park_admin").first()
if not admin_user:
    create_admin = models.UserModel(
        username="******",
        password=models.UserModel.generate_hash("sk8park_admin"))
    create_admin.save_to_db()


@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
    jti = decrypted_token['jti']
    return models.RevokedTokenModel.is_jti_blacklisted(jti)
Beispiel #12
0
 def setUp(self):
     self.UserModel = models.UserModel()
@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
    jti = decrypted_token['jti']
    return models.RevokedTokenModel.is_jti_blacklisted(jti)


import models, resources

api.add_resource(resources.UserRegistration, '/v1/users')
api.add_resource(resources.UserLogin, '/v1/login')
api.add_resource(resources.TokenOperations, '/v1/token')
api.add_resource(resources.TokenVerification, '/v1/protected')

# Add 2 users:
if not models.UserModel.find_by_username('test'):
    new_user = models.UserModel(
        username='******', password=models.UserModel.generate_hash('test'))
    new_user.save_to_db()

if not models.UserModel.find_by_username('admin'):
    new_user = models.UserModel(
        username='******', password=models.UserModel.generate_hash('admin'))
    new_user.save_to_db()

if not models.UserModel.find_by_username('sensor'):
    new_user = models.UserModel(
        username='******', password=models.UserModel.generate_hash('sensor'))
    new_user.save_to_db()

if not models.UserModel.find_by_username('monitor'):
    new_user = models.UserModel(
        username='******', password=models.UserModel.generate_hash('monitor'))