Example #1
0
def authenticate(provider_id, access_token, **kwargs):
    provider_id = provider_id.lower()
    if provider_id == 'google':
        me = google.get('userinfo', token=(access_token, ''))
        auth_data = {
            'name': me.data['name'],
            'email': me.data['email'],
            'picture_url': me.data['picture'],
            'provider_id': 'google',
            'provider_user_id': me.data['id']
        }
    elif provider_id == 'facebook':
        me = facebook.get(
            '/me/?fields=email,name,id,picture.height(200).width(200)',
            token=(access_token, ''))
        auth_data = {
            'name': me.data['name'],
            'email': me.data['email'],
            'picture_url': me.data['picture']['data']['url'],
            'provider_id': 'facebook',
            'provider_user_id': me.data['id']
        }
    else:
        return 'Invalid Provider Id'

    return set_user(auth_data)
Example #2
0
def authenticate(provider_name, access_token, **kwargs):

    if provider_name == 'google':
        me = google.get('userinfo', token=(access_token, ''))
        if 'error' in me.data:
            return jsonify({'error': me.data['error']})
        auth_data = {
            'name': me.data['name'],
            'email': me.data['email'],
            'picture_url': me.data['picture'],
            'provider_name': 'google',
            'provider_user_id': me.data['id']
        }

    elif provider_name == 'facebook':
        me = facebook.get('/me/?fields=email,name,id,picture.height(200).width(200)', token=(access_token, ''))
        if 'error' in me.data:
            return jsonify({'error': me.data['error']})
        auth_data = {
            'name': me.data['name'],
            'email': me.data['email'],
            'picture_url': me.data['picture']['data']['url'],
            'provider_name': 'facebook',
            'provider_user_id': me.data['id']
        }
    else:
        return jsonify({'error': 'Invalid Provider Id'})

    social_login = SocialLogin.query.filter_by(
        provider_name=auth_data['provider_name'],
        provider_user_id=auth_data['provider_user_id']
    ).first()

    # In case there's a login without a user
    if social_login is not None and social_login.user is None:
        social_login.delete()
        social_login = None

    is_new_user = False

    if social_login is None:
        is_new_user = True
        new_user = User(
            public_id=str(uuid.uuid4()),
            name=auth_data['name'],
            email=auth_data['email'],
            picture_url=auth_data['picture_url'],
        )

        social_login = SocialLogin(
            user=new_user,
            provider_name=auth_data['provider_name'],
            provider_user_id=auth_data['provider_user_id'],
        )
        db.session.add(new_user)
        db.session.commit()

    user = social_login.user
    return user
Example #3
0
 def decorated_function(*args, **kwargs):
     emails = user_list
     if 'google_token' in session:
         me = google.get('userinfo')
         user = {"data": me.data}
         if user['data']['email'] in emails:
             return view_function(*args, **kwargs)
     abort(401)
Example #4
0
def g_authorized():
    resp = google.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'], request.args['error_description'])
    session['google_token'] = (resp['access_token'], '')
    me = google.get('userinfo')
    return set_user('Google', me)
Example #5
0
def index():
    if 'google_token' in session:
        me = google.get('userinfo')
        user = models.getUser(me.data['email'])
        if not user:
            models.createUser(me.data['email'])
        return render_template('index.html',user=me.data)
    #don't know you, so log in
    return redirect(url_for('login'))
Example #6
0
def g_authorized():
    resp = google.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    session['google_token'] = (resp['access_token'], '')
    me = google.get('userinfo')
    return set_user('Google', me)
Example #7
0
def authorized():
    resp = google.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'], request.args['error_description'])
    session['google_token'] = (resp['access_token'], '')
    me = google.get('userinfo')
    # return jsonify({"data": me.data})
    permissions.update_user()
    return redirect(url_for('index'))
Example #8
0
def authorized(response):
    '''Handles the OAuth response from Google
    Returns: a redirect to the index page, after logging the user in (or erroring)
    '''
    if response is None:
        flash('Login failed :(')
        return redirect(url_for('main.index'))

    session['google_token'] = (response['access_token'], '')
    me = google.get('userinfo')

    #is the user either from RIT or explicitly allowed?
    alloweduser = AllowedUser.query.filter_by(email=me.data['email'], ban=False).first()
    if me.data['hd'] != "g.rit.edu" and alloweduser is None:
        me = None
        response = None
        logout_user()
        session.clear()
        flash('You must log in with your RIT Email \
              or obtain special permission to log in from an administrator')
        return redirect(url_for('main.index'))

    #get the existing user, or create a new one
    user = User.query.filter_by(email=me.data['email']).first()
    if user is None:
        if me.data['name']:
            nickname = me.data['name']
        elif me.data['given_name']:
            nickname = me.data['given_name']
        else:
            #Use everything up to @ for username (RIT ID)
            nickname = me.data['email'].split('@')[0][:10]
        #if the email address > 10 digits truncate
        username = me.data['email'].split('@')[0][:10]
        #if the username already exists mainend a random integer to the end
        while User.query.filter_by(username=username).first() is not None:
            username = username[:7] + str(randint(100, 999))
        user = User(nickname=nickname,
                    username=username,
                    email=me.data['email'],
                    role=USER_ROLES['user'])
        db.session.add(user)
        db.session.commit()
    if me.data['name'] and user.nickname is not me.data['name']:
        user.nickname = me.data['name']
        db.session.add(user)
        db.session.commit()
    elif me.data['given_name'] and user.nickname is not me.data['name']:
        user.nickname = me.data['given_name']
        db.session.add(user)
        db.session.commit()
    login_user(user, remember = False)
    return redirect(request.args.get('next') or url_for('main.index'))
Example #9
0
def answer():
    if 'google_token' in session:
        me = google.get('userinfo')
        user = models.getUser(me.data['email'])
        answer = request.form['essay']
        Aform = forms.Eform()
        if Aform.validate_on_submit():
            #send the answer to the student's data
            models.putAnswer(user['email'], answer)
            #go to next question
        return redirect(url_for('question'))

    return redirect(url_for('login'))
Example #10
0
def authorized():
    resp = google.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    session['google_token'] = (resp['access_token'], '')
    me = google.get('userinfo')
    #return jsonify({"data": me.data})
    if me:
        return redirect(url_for('index'))
    else:
        return 'Access denied.'
Example #11
0
def google_authorized(resp, est):
    if resp is None:
        msg.flash(
            'Access denied: reason=%s error=%s' %
            (request.args['error_reason'], request.args['error_description']))
        return redirect(url_for('index'))
    if str(type(resp)) == "<class 'flask_oauthlib.client.OAuthException'>":
        msg.flash('Access denied: desc=%s error=%s' %
                  (resp.data['error_description'], resp.data['error']))
        return redirect(url_for('index'))
    session['google_token'] = (resp['access_token'], '')
    person = google.get('userinfo')
    # person.data = {
    #     u'family_name': last_name,
    #     u'name': full_name,
    #     u'picture': url,
    #     u'gender': u'male' or u'female',
    #     u'email': email_addr,
    #     u'link': google_plus_url,
    #     u'given_name': first_name,
    #     u'id': u'101149719268028298009',
    #     u'hd': domain_name,
    #     u'verified_email': True  }
    session.pop('_flashes', None)
    email = person.data[u'email']
    authid = person.data[u'id']
    # picture_url = person.data[u'picture']
    if est == "new":
        user = database.create_user_byOAuth(email, authid, "google")
        if msg.is_bad(user):
            msg.flash(user)
            return redirect(url_for('index'))
        account = account__database.create_account(user, person.data[u'name'])
        if msg.is_bad(account):
            msg.flash(account)
            return redirect(url_for('index'))
        login_user(user)
        msg.flash(
            msg.success(
                'Welcome, your name has been determined to be <b>{}</b>'.
                format(account.s_name),
                return_def="index"))
        return redirect(url_for('index'))
    user = database.read_user_byOAuth(email, authid, "google")
    if msg.is_bad(user):
        msg.flash(user)
        return redirect(url_for('index'))
    login_user(user)
    msg.flash(msg.success('Welcome back.', return_def="index"))
    return redirect(url_for('index'))
Example #12
0
def authorized():
    resp = google.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'], request.args['error_description'])
    session['google_token'] = (resp['access_token'], '')
    user = google.get('userinfo').data
    user = User.objects(email=user['email']).modify(
        set__name=user['name'],
        set__profile=user['picture'],
        set__last_login=datetime.utcnow(),
        new=True,
        upsert=True)
    session['user'] = user
    return redirect(url_for('home'))
Example #13
0
def before_request():
    g.user = None
    print g.user
    if "user_id" in session:
        g.user = User.query.get(session["user_id"])

    #TODO i think this needs to be removed
    elif 'google_token' in session:
        user_data = google.get("userinfo")
        username = user_data.data.get("email")
        if username:
            username = username.split('@')[0]
            user = User.query.filter(User.username == username).first()
            if user:
                user_id = user.id
                g.user = User.query.get(user_id)
Example #14
0
def google_login():
    if not google.authorized:
        return redirect(url_for("google.login"))
    resp = google.get("/oauth2/v1/userinfo")
    assert resp.ok, resp.text

    user = UserModel.query.filter_by(username=resp.json()["name"]).first()

    # Add user to the database if not already there
    if user is None:
        user = UserModel(username=resp.json()["name"])
        db.session.add(user)
        db.session.commit()
        user = UserModel.query.filter_by(username=resp.json()["name"]).first()

    login_user(user)
    return render_template('index.html')
Example #15
0
def question():
    if 'google_token' in session:
        me = google.get('userinfo')
        user = models.getUser(me.data['email'])
        if not user:
            return 'You must be signed in with School\'s Google account'

        #get the question and see if any questions left
        question = models.getQuestion(user)

        if not question:
            user['finished'] = 'true'
            models.updateUser(user)
            return 'You are done with the Questions. Let your teacher know.'

        form = forms.Eform()
        return render_template('question.html', form=form, user=user, question=question)

    return redirect(url_for('login'))
Example #16
0
 def update_user(self):
     try:
         if 'google_token' in session:
             self.login = True
             self.current_user = google.get('userinfo').data
             self.current_user_email = self.current_user['email']
             self.current_user_name = self.current_user['given_name']
             if self.current_user_email and self.current_user_email in Permissions.approved_emails:
                 self.authorized = True
         else:
             self.login = False
             self.authorized = False
             self.current_user = None
             self.current_user_email = None
             self.current_user_name = None
     except:
         self.login = False
         self.authorized = False
         self.current_user = None
         self.current_user_email = None
         self.current_user_name = None
Example #17
0
def authorized():
    resp = google.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'], request.args['error_description'])
    session['google_token'] = (resp['access_token'], '')
    user_info = google.get('userinfo')
    user_data = user_info.data
    email = user_data.get('email')
    username = email.split('@')[0]
    user = User.query.filter(User.username == str(username)).first()
    if user:
        session["user_id"] = user.id
        return redirect(url_for('user', username=user.username))
    else:
        user = User(username=username)
        user.email = email
        db.session.add(user)
        db.session.commit()
        g.user = user
        return redirect(url_for('user', username=user.username))
    return render_template('index.html')
Example #18
0
def authorized(response):
    if response is None:
        flash("Login failed", category='error')
        return redirect(url_for("main.index"))
    session['google_token'] = (response['access_token'], '')
    me = google.get('userinfo')

    if me.data['email'][-9:].lower() != "kdrib.org":
        me = None
        response = None
        logout_user()
        session.clear()
        flash("Log in with your @kdrib.org account!", category="warning")
        return redirect(url_for('main.index'))
    bro = Brother.query.filter_by(email=me.data['email']).first()
    if bro is None:
        bro = Brother(name=me.data.get("name", ""), nickname="", email=me.data['email'], position=None, pin=0)
        db.session.add(bro)
        db.session.commit()
    login_user(bro, remember = False)
    if bro.pin == 0 or bro.family is None:
        return redirect(url_for('main.first_login'))
    return redirect(url_for("main.index"))
Example #19
0
def login():
    # these parameters will be needed in multiple paths
    LDAP_ENABLED = True if 'LDAP_TYPE' in app.config.keys() else False
    LOGIN_TITLE = app.config[
        'LOGIN_TITLE'] if 'LOGIN_TITLE' in app.config.keys() else ''
    BASIC_ENABLED = app.config['BASIC_ENABLED']
    SIGNUP_ENABLED = app.config['SIGNUP_ENABLED']
    GITHUB_ENABLE = app.config.get('GITHUB_OAUTH_ENABLE')
    GOOGLE_ENABLE = app.config.get('GOOGLE_OAUTH_ENABLE')
    SAML_ENABLED = app.config.get('SAML_ENABLED')

    if g.user is not None and current_user.is_authenticated:
        return redirect(url_for('dashboard'))

    if 'google_token' in session:
        user_data = google.get('userinfo').data
        first_name = user_data['given_name']
        surname = user_data['family_name']
        email = user_data['email']
        user = User.query.filter_by(username=email).first()
        if not user:
            # create user
            user = User(username=email,
                        firstname=first_name,
                        lastname=surname,
                        plain_text_password=None,
                        email=email)
            user.create_local_user()

        session['user_id'] = user.id
        login_user(user, remember=False)
        session['external_auth'] = True
        return redirect(url_for('index'))

    if 'github_token' in session:
        me = github.get('user')
        user_info = me.data
        user = User.query.filter_by(username=user_info['name']).first()
        if not user:
            # create user
            user = User(username=user_info['name'],
                        plain_text_password=None,
                        email=user_info['email'])
            user.create_local_user()

        session['user_id'] = user.id
        session['external_auth'] = True
        login_user(user, remember=False)
        return redirect(url_for('index'))

    if request.method == 'GET':
        return render_template('login.html',
                               github_enabled=GITHUB_ENABLE,
                               google_enabled=GOOGLE_ENABLE,
                               saml_enabled=SAML_ENABLED,
                               ldap_enabled=LDAP_ENABLED,
                               login_title=LOGIN_TITLE,
                               basic_enabled=BASIC_ENABLED,
                               signup_enabled=SIGNUP_ENABLED)

    # process login
    username = request.form['username']
    password = request.form['password']
    otp_token = request.form.get('otptoken')
    auth_method = request.form.get('auth_method', 'LOCAL')

    # addition fields for registration case
    firstname = request.form.get('firstname')
    lastname = request.form.get('lastname')
    email = request.form.get('email')
    rpassword = request.form.get('rpassword')

    if None in [firstname, lastname, email]:
        #login case
        remember_me = False
        if 'remember' in request.form:
            remember_me = True

        user = User(username=username,
                    password=password,
                    plain_text_password=password)

        try:
            auth = user.is_validate(method=auth_method)
            if auth == False:
                return render_template('login.html',
                                       error='Invalid credentials',
                                       ldap_enabled=LDAP_ENABLED,
                                       login_title=LOGIN_TITLE,
                                       basic_enabled=BASIC_ENABLED,
                                       signup_enabled=SIGNUP_ENABLED,
                                       github_enabled=GITHUB_ENABLE,
                                       saml_enabled=SAML_ENABLED)
        except Exception, e:
            error = e.message['desc'] if 'desc' in e.message else e
            return render_template('login.html',
                                   error=error,
                                   ldap_enabled=LDAP_ENABLED,
                                   login_title=LOGIN_TITLE,
                                   basic_enabled=BASIC_ENABLED,
                                   signup_enabled=SIGNUP_ENABLED,
                                   github_enabled=GITHUB_ENABLE,
                                   saml_enabled=SAML_ENABLED)

        # check if user enabled OPT authentication
        if user.otp_secret:
            if otp_token:
                good_token = user.verify_totp(otp_token)
                if not good_token:
                    return render_template('login.html',
                                           error='Invalid credentials',
                                           ldap_enabled=LDAP_ENABLED,
                                           login_title=LOGIN_TITLE,
                                           basic_enabled=BASIC_ENABLED,
                                           signup_enabled=SIGNUP_ENABLED,
                                           github_enabled=GITHUB_ENABLE,
                                           saml_enabled=SAML_ENABLED)
            else:
                return render_template('login.html',
                                       error='Token required',
                                       ldap_enabled=LDAP_ENABLED,
                                       login_title=LOGIN_TITLE,
                                       basic_enabled=BASIC_ENABLED,
                                       signup_enabled=SIGNUP_ENABLED,
                                       github_enabled=GITHUB_ENABLE,
                                       saml_enabled=SAML_ENABLED)

        login_user(user, remember=remember_me)
        return redirect(request.args.get('next') or url_for('index'))
Example #20
0
def login():
    if not google.authorized:
        return redirect(url_for('google.login'))
    resp = google.get("/oauth2/v2/userinfo")
    assert resp.ok, resp.text
    return "You are {email} on Google".format(email=resp.json()["email"])