Exemple #1
0
def email_signin(email, password):
    """
    Signin with an email and a password.

    :param email: email address (str)
    :param password: unhashed password (str)
    :returns: User (obj) or status message, HTTP code
    """
    user = User.get_byemail(email)

    if not user:
        return "Account doesn't exists, please register", 401

    # check if authentication method by email exists for this user
    auth_id = 'email${}'.format(user.id)
    user_auth = UserAuth.exists(auth_id)
    if not user_auth:
        return "Existing user with google or facebook account, not email", 401

    # check password validity
    if not pbkdf2_sha256.verify(password, user_auth.password):
        return "Incorrect password", 401

    user.update_apikey(User.generate_apikey(user.email))

    resp = {
        'auth_id': auth_id,
    }
    resp.update(user.json)

    return resp, 200
Exemple #2
0
def email_register(email=None,
                   password=None,
                   name=None,
                   gender=None,
                   birthyear=None,
                   image_url=None):
    """
    Signup with an email and password.

    :param email: email address (str)
    :param password: unhashed password (str)
    :param name: user's full name (opt str)
    :param gender: gender (opt str)
    :param birthyear: birth year (opt str)
    :param image_url: URL to user profile image (opt str)
    :returns: User (obj) or status message, HTTP code
    """
    email = email.lower()
    user = User.get_byemail(email)
    if user:
        return "User already exists", 409

    # primary user doesn't exists, creating it
    user = User.add_user(name=name,
                         email=email,
                         gender=gender,
                         image_url=image_url)

    # add an authentification method
    auth_id = 'email${}'.format(user.id)
    UserAuth.add_userauth(user_id=user.id,
                          name=name,
                          auth_id=auth_id,
                          email=email,
                          auth_type='email',
                          password=pbkdf2_sha256.encrypt(password,
                                                         rounds=200,
                                                         salt_size=16),
                          fullprofile={'birthyear': birthyear})

    # login user in the current session
    login_user(user, True)

    resp = {
        'auth_id': auth_id,
    }
    resp.update(user.json)

    return resp, 201
Exemple #3
0
Fichier : v1.py Projet : prkng/api
 def post(self):
     """
     Send an account password reset code
     """
     args = passwd_reset_parser.parse_args()
     user = User.get_byemail(args["email"].lower())
     if not user:
         return "Account not found", 400
     return UserAuth.send_reset_code("email${}".format(user.id), user.email)
Exemple #4
0
Fichier : v1.py Projet : prkng/api
 def post(self):
     """Send analytics event data"""
     args = hello_parser.parse_args()
     args['push_on_temp_restriction'] = args[
         'push_on_temp_restriction'] not in ['false', 'False', False]
     u = User.get(g.user.id)
     u.hello(args.get('device_type'), args.get('device_id'),
             args.get('lang'), args.get('push_on_temp_restriction'))
     return "Hello there!", 200
Exemple #5
0
        def wrapper(*args, **kwargs):
            apikey = request.headers.get(HEADER_API_KEY)
            if not apikey:
                return 'Invalid API Key', 401

            g.user = User.get_byapikey(apikey)
            if not g.user:
                return 'Invalid API Key', 401

            return func(*args, **kwargs)
Exemple #6
0
Fichier : v1.py Projet : prkng/api
 def post(self):
     """
     Change an account's password via reset code
     """
     args = passwd_change_parser.parse_args()
     user = User.get_byemail(args["email"])
     if not user:
         return "Account not found", 404
     if not UserAuth.update_password("email${}".format(user.id),
                                     args["passwd"], args["code"]):
         return "Reset code incorrect", 400
Exemple #7
0
def send_push():
    """
    Send push notifications by user ID
    """
    device_ids = []
    data = request.get_json()
    if data["user_ids"]:
        for x in data["user_ids"]:
            x = x.strip()
            if x in ["all", "ios", "android", "en", "fr"]:
                device_ids.append("all")
            elif x.startswith("arn:aws:sns:"):
                device_ids.append(x)
            else:
                u = User.get(x)
                if u and u.sns_id:
                    device_ids.append(u.sns_id)
        schedule_notifications(device_ids, data.get('text'))
        return jsonify(device_ids=device_ids), 200
    else:
        return "No user IDs supplied", 400
Exemple #8
0
def get_users():
    """
    Get a list of users
    """
    users = User.get_all()
    return jsonify(users=users), 200
Exemple #9
0
 def auto_login():
     User.get(1)
     return "ok"
Exemple #10
0
def app(request):
    app = create_app(env='Testing')

    init_model(app)
    init_api(app)
    init_login(app)

    # Establish an application context before running the tests.
    ctx = app.app_context()
    ctx.push()

    def teardown():
        metadata.drop_all()
        db.engine.execute("drop table if exists slots")
        ctx.pop()

    request.addfinalizer(teardown)

    # hack to cause a new request context to be pushed and have a current user logged in
    @app.route('/test_auto_login')
    def auto_login():
        User.get(1)
        return "ok"

    # create slots table
    db.engine.execute("""
        CREATE TABLE IF NOT EXISTS slots
        (
          id serial PRIMARY KEY,
          city varchar,
          rid integer,
          signposts integer[],
          rules jsonb,
          way_name varchar,
          geom geometry(LineString,3857),
          geojson jsonb,
          button_location jsonb,
          button_locations jsonb
        )
    """)

    with app.test_client() as client:
        # add a user in order to honor foreign key of checkins
        g.user = User.add_user(email='test@test', name='test_user')
        client.get("/test_auto_login")

    db.engine.execute("""
        DROP TABLE IF EXISTS cities;
        CREATE TABLE cities AS
            SELECT 'montreal' AS name,
             'POLYGON((4.28302949061661931 42.34791957104560112,
                4.28302949061661931 44.39724932975872917,
                1.43423592493298013 44.44228954423594047,
                1.31037533512064774 42.483040214477235,
                4.28302949061661931 42.34791957104560112))'::GEOMETRY AS geom
    """)

    # add some checkins
    db.engine.execute("truncate table checkins")
    for num in range(3):
        db.engine.execute("""
            INSERT INTO slots (geom)
            VALUES('SRID=3857;LINESTRING(2.765 42.988, 2.865 43.988)'::geometry)
            """.format(num))
        db.engine.execute("""
            INSERT INTO checkins (user_id, slot_id, long, lat)
            VALUES(1, {}, 2.765, 42.988)""".format(num))

    return app
Exemple #11
0
def load_user(id):
    return User.get(int(id))
Exemple #12
0
def google_signin(access_token):
    """
    Authorize user via Google Login.
    Add to the DB as authentication method if not already present.

    :param access_token: access token as returned from Google login window on client (str)
    :returns: User (obj) or status message, HTTP code
    """
    # verify access token has been requested with the correct app id
    if access_token.startswith("eyJh"):
        # Google Sign-In (1.3.1+)
        resp = requests.get("https://www.googleapis.com/oauth2/v3/tokeninfo",
                            params={'id_token': access_token})
        data = resp.json()
        if resp.status_code != 200:
            return data, resp.status_code

        if data['aud'] not in [
                current_app.config['OAUTH_CREDENTIALS']['google']['ios_id'],
                current_app.config['OAUTH_CREDENTIALS']['google']['android_id']
        ]:
            return "Authentication failed.", 401

        me = {}
        id, email, name, picture = data['sub'], data['email'], data[
            'name'], data.get('picture', '')
        first_name, last_name = data.get('given_name',
                                         ''), data.get('family_name', '')
    else:
        # Google OAuth 2.0 (1.3 and below)
        resp = requests.get("https://www.googleapis.com/oauth2/v1/tokeninfo",
                            params={'access_token': access_token})
        data = resp.json()
        if resp.status_code != 200:
            return data, resp.status_code

        if data['audience'] != current_app.config['OAUTH_CREDENTIALS'][
                'google']['id']:
            return "Authentication failed.", 401

        # get user profile
        resp = requests.get("https://www.googleapis.com/oauth2/v1/userinfo",
                            params={'access_token': access_token})

        me = resp.json()
        if resp.status_code != 200:
            return me, resp.status_code

        if 'email' not in me:
            return 'Email information not provided, cannot register user', 401

        id, email, name, picture = me['id'], me['email'], me['name'], me.get(
            'picture', '')
        first_name, last_name = me.get('given_name',
                                       ''), me.get('family_name', '')

    auth_id = 'google${}'.format(id)

    # known google account ?
    user_auth = UserAuth.exists(auth_id)

    # check if user exists with its email as unique identifier
    user = User.get_byemail(email)
    if not user:
        # primary user doesn't exists, creating it
        user = User.add_user(name=name,
                             first_name=first_name,
                             last_name=last_name,
                             email=email,
                             gender=None,
                             image_url=picture)

    if not user_auth:
        # add user auth informations
        UserAuth.add_userauth(user_id=user.id,
                              name=user.name,
                              auth_id=auth_id,
                              email=user.email,
                              auth_type='google',
                              fullprofile=me)
    else:
        # if already exists just update with a new apikey and profile details
        user.update_apikey(User.generate_apikey(user.email))
        user.update_profile(name=name, email=email, image_url=picture)

    # login user (powered by flask-login)
    login_user(user, True)

    resp = {
        'auth_id': auth_id,
    }
    resp.update(user.json)

    return resp, 200
Exemple #13
0
def facebook_signin(access_token):
    """
    Authorize user via Facebook oAuth login.
    Add to the DB as authentication method if not already present.

    :param access_token: access token as returned from Facebook login window on client (str)
    :returns: User (obj) or status message, HTTP code
    """
    # verify access token has been requested with the correct app id
    resp = requests.get("https://graph.facebook.com/app/",
                        params={'access_token': access_token})
    data = resp.json()

    if resp.status_code != 200:
        return data, resp.status_code

    if data['id'] != current_app.config['OAUTH_CREDENTIALS']['facebook']['id']:
        return "Authentication failed.", 401

    # get user profile
    resp = requests.get("https://graph.facebook.com/me",
                        params={
                            'access_token':
                            access_token,
                            'fields':
                            'id,email,name,first_name,last_name,gender,picture'
                        })
    me = resp.json()

    if resp.status_code != 200:
        return me, resp.status_code

    if 'email' not in me:
        return 'Email information not provided, cannot register user', 401

    # check if user exists with its email as unique identifier
    user = User.get_byemail(me['email'])
    if not user:
        # primary user doesn't exists, creating it
        user = User.add_user(name=me['name'],
                             first_name=me['first_name'],
                             last_name=me['last_name'],
                             email=me['email'],
                             gender=me.get('gender', None),
                             image_url=me["picture"]["data"]["url"]
                             if me.get('picture') else '')
    else:
        # if already exists just update with a new apikey and profile pic
        user.update_apikey(User.generate_apikey(user.email))
        user.update_profile(image_url=me["picture"]["data"]["url"] if me.
                            get('picture') else '')
    # known facebook account ?
    auth_id = 'facebook${}'.format(me['id'])
    user_auth = UserAuth.exists(auth_id)

    if not user_auth:
        # add user auth informations
        UserAuth.add_userauth(user_id=user.id,
                              name=user.name,
                              auth_id=auth_id,
                              email=user.email,
                              auth_type='facebook',
                              fullprofile=me)

    # login user (powered by flask-login)
    login_user(user, True)

    resp = {
        'auth_id': auth_id,
    }
    resp.update(user.json)

    return resp, 200