Example #1
0
def before_request_func():
    try:
        newmail = storage.get(User, session['id'])
        if newmail:
            session.update({'email': newmail.email})
    except:
        pass
Example #2
0
def output():
    """ Logic for handling the refinement. Gets the AJAX call and file type 
        format, creates a temporary file for the picture passes it to webscript
        refinement checker URL passes the result back.
        If the user chooses to generate GO lang pass to go lang tool and pass
        back
    """
    if request.args.get('c', 0, type=str) == 'false':
        try:
            a = request.args.get('a', 0, type=str)
            session.update({'currentScript': str(a)})
            format = str(request.args.get('b', 0, type=str))
            tf = tempfile.NamedTemporaryFile().name
            script_response = web_script_refinement_checker(str(a), tf, format)
            tf = "files/imagetemp" + tf + "." + format
            return jsonify(result=Markup(script_response),
                           image=url_for('static', filename=tf))
        except:
            return handle_404_json_error(404)
    else:
        try:
            a = request.args.get('a', 0, type=str)
            automata_list = load_automata(a)
            golang_line = generate_go_lang(automata_list)
            return jsonify(result=Markup(golang_line))
        except:
            return handle_404_json_error(404)
Example #3
0
def do_login():
    # The request has to have an assertion for us to verify
    if 'assertion' not in request.form:
        # TODO: this may be overkill - or not for REST API
        abort(400)
 
    # Send the assertion to Mozilla's verifier service.
    data = {'assertion': request.form['assertion'],
            'audience': BASE_URL}
    resp = requests.post('https://verifier.login.persona.org/verify',
                         data=data,
                         verify=True)
 
    # Did the verifier respond?
    if resp.ok:
        # Parse the response
        verification_data = json.loads(resp.content)
 
        # Check if the assertion was valid
        if verification_data['status'] == 'okay':
            # Log the user in by setting a secure session cookie
            session.update({'email': verification_data['email']})

            # TODO: store this in a better way
            current_user['email'] = verification_data['email']

            # TODO: hand back a full json object for the user.
            return verification_data['email'];
 
    # Oops, something failed. Abort.
    abort(500)
Example #4
0
def OAuth2Callback(provider):
    print('--- OAuth2Callback called for IP : ' + provider)

    code = request.args.get('code', 'unknown')
    if (code == 'unknown'):
        result = render_template('error.html')
    else:
        credentials, profile = getIdentityProvider(provider).oauthCallback(
            code)

        import urllib
        # _scheme is required for SSL, see
        # https://github.com/mitsuhiko/flask/issues/773
        #url = url_for('s3', _scheme="https", _external=True, **dict(credentials.items() + profile.items()))
        url = url_for('s3', _scheme="https", _external=True)
        #print('--- redirect url : ' + url)

        # save credentials and profile in the server side session
        session.update(credentials)
        session.update(profile)
        #print('--- session : ' + str(session))

        result = redirect(url)

    return result
Example #5
0
def select_geo():
    if not session.get('file'):
        return redirect(url_for('views.index'))
    context = {}
    if request.method == 'POST':
        inp = StringIO(session['file'])
        reader = UnicodeCSVReader(inp)
        header = reader.next()
        fields = {}
        geo_type = None
        valid = True
        if not request.form:
            valid = False
            context['errors'] = ['Select a field that contains a geography type']
        else:
            for k,v in request.form.items():
                if k.startswith("geotype"):
                    geo_type = v
                    index = int(k.split('_')[1])
                    fields[header[index]] = {
                        'geo_type': v,
                        'column_index': index
                    }

            found_geo_type = get_geo_types(geo_type)[0]['info']
            sample_as_list = session['sample_data'][index][2].split(', ')
            valid = validate_geo_type(found_geo_type, sample_as_list)
            context['errors'] = ['The column you selected must be formatted like "%s" to match on %s geographies. Please pick another column or change the format of your data.' % (found_geo_type.formatting_example, found_geo_type.human_name)]
        if valid:
            mancer_data = get_data_sources(geo_type)
            session.update({'fields': fields, 'mancer_data': mancer_data})
            return redirect(url_for('views.select_tables'))
    return render_template('select_geo.html', **context)
Example #6
0
    def handle_state_phone_number(self):
        session[Keys.FORGET_PASS][Keys.USER_ID] = self.phone_number
        user = User.find(phone_number=session[Keys.FORGET_PASS][Keys.USER_ID])
        if not user[0]:
            dct = user[1].dictionary_creator()
            return self.serialize(dct, self.converter)

        if len(user[1]) == 0:
            return self.create_no_user_dct(
                Result.language.NOT_REGISTERED_BEFORE)

        sms = SMSCodeValidation(user[1][0].name, self.phone_number,
                                SMSCodeValidation.create_random_code())
        _, code = sms.send_validation_code()

        result = self.create_success_message(
            Result.language.CODE_SEND_SUCCESSFULLY)
        dct = result.dictionary_creator()
        session.update({
            Keys.FORGET_PASS: {
                Keys.STATE_ID: States.CODE,
                Keys.CODE: str(code),
                Keys.USER_ID: self.phone_number,
                Keys.TYPE_USER: self.type_user,
                Keys.NAME: user[1][0].name
            }
        })
        return self.serialize(dct, self.converter)
Example #7
0
    def handle_state_code(self):
        if self.code == session[Keys.FORGET_PASS][Keys.CODE]:
            user_id = session[Keys.FORGET_PASS][Keys.USER_ID]
            session.update({
                Keys.FORGET_PASS: {
                    Keys.STATE_ID: States.PASSWORD,
                    Keys.USER_ID: user_id,
                    Keys.TYPE_USER: self.type_user
                }
            })
            result = self.create_success_message(
                Result.language.CODE_RECEIVE_SUCCESSFULLY)
            dct = result.dictionary_creator()
            return self.serialize(dct, self.converter)
        session.update({
            Keys.FORGET_PASS: {
                Keys.STATE_ID: States.RESEND_CODE,
                Keys.USER_ID: session[Keys.FORGET_PASS][Keys.PHONE_NUMBER],
                Keys.TYPE_USER: self.type_user,
                Keys.NAME: session[Keys.FORGET_PASS][Keys.NAME]
            }
        })

        result = self.create_fail_message(Result.language.CODE_RECEIVE_FAILED)
        dct = result.dictionary_creator()
        return self.serialize(dct, self.converter)
Example #8
0
def add_bill():
    form = get_billform_form(g.project)
    if g.project.advanced_weighting_enabled:
        form.advanced = True

    if request.method == "POST":

        if form.validate():
            # save last selected payer in session
            session["last_selected_payer"] = form.payer.data
            session.update()

            bill = Bill()
            db.session.add(form.save(bill))
#            for
            db.session.commit()

            flash(_("The bill has been added"))

            args = {}
            if form.submit2.data:
                args["add_bill"] = True

            return redirect(url_for(".list_bills", **args))

    return render_template("add_bill.html", form=form)
Example #9
0
def sso_lander_view(group):
    """
    Log a user into the system using a signed and encrypted get argument "token".

    Here a ttl of 60 seconds is life. See
    https://cryptography.io/en/latest/fernet/#cryptography.fernet.Fernet.decrypt.
    """
    secret = redis_cli.get('secret:{}'.format(group))
    if not secret:
        return 'group not found', 404
    fernet = Fernet(secret)

    token = request.args.get('token', '').encode('utf8')
    try:
        data = fernet.decrypt(token, ttl=60)
    except InvalidToken:
        return '403: Invalid Token', 403

    try:
        data = json.loads(data.decode('utf8'))
    except JSONDecodeError:
        return '400: problem parsing json', 400
    data['referrer'] = request.referrer
    session.update(
        profile=data,
        group=group,
    )

    group_key = 'info:{}'.format(group)
    redis_cli.lpush(group_key, '{nm} ({rt}) logged in at {dt:%Y-%m-%d %H:%M:%S}'.format(dt=datetime.now(), **data))
    return redirect('/')
Example #10
0
def frmLogin_post():
    realms = session.get('realms')
    confirm = session.get('confirm')
    token_form = session.get('token_form')
    roles = session.get('roles')
    if realms:
        assert 0 <= int(request.form.get('realm', -1)) < len(realms)
    session.update(step='POST-login', username=request.form.get('username'),
                   password=request.form.get('password'),
                   realm=request.form.get('realm'))
    # print(session)

    need_confirm = need_token = False
    got_confirm = got_token = None
    if confirm:
        need_confirm = request.form.get('btnContinue') is None
        got_confirm = not need_confirm
    if token_form:
        need_token = request.form.get('btnAction') is None and request.form.get('totpactionEnter') is None and request.form.get('token_as_second_password') is None
        got_token = not need_token
    session.update(got_token=got_token, got_confirm=got_confirm)

    if need_token and not got_confirm:
        return redirect(url_for('frm2FA'))
    elif need_confirm:
        return redirect(url_for('frmConfirmation'))
    elif roles:
        return redirect(url_for('frmSelectRoles'))
    else:
        resp = redirect(url_for('webtop'))
        resp.set_cookie('DSID', cookify(dict(session)))
        return resp
Example #11
0
def index():
    if request.method == 'GET':
        return render_template('index.html',
                               name=session.get('name', ''),
                               phone=session.get('phone', '')
                               )

    params = {}
    params['name'] = request.form['name']
    params['phone'] = request.form['phone']
    params['start_time'] = datetime.datetime.utcnow()  # USE UTC time!
    params['tz_offset'] = request.form['tz_offset']
    session.update(params)

    try:
        instance, is_new = get_or_create_user(db.session, UserData, **params)
        db.session.flush()
    except IntegrityError:
        db.session.rollback()
        flash("Name and phone number don't match. Try again.")
        return render_template('index.html',
                               name=session.get('name', ''),
                               phone=session.get('phone', '')
                               )

    return redirect(url_for('info'))
Example #12
0
def admin():
    """Admin authentication.

    When ADMIN_PASSWORD is empty, admin authentication is deactivated.
    """
    form = AdminAuthenticationForm()
    goto = request.args.get('goto', url_for('.home'))
    is_admin_auth_enabled = bool(current_app.config['ADMIN_PASSWORD'])
    if request.method == "POST":
        client_ip = request.remote_addr
        if not login_throttler.is_login_allowed(client_ip):
            msg = _("Too many failed login attempts, please retry later.")
            form.errors['admin_password'] = [msg]
            return render_template("admin.html", form=form, admin_auth=True,
                                   is_admin_auth_enabled=is_admin_auth_enabled)
        if form.validate():
            # Valid password
            if (check_password_hash(current_app.config['ADMIN_PASSWORD'],
                                    form.admin_password.data)):
                session['is_admin'] = True
                session.update()
                login_throttler.reset(client_ip)
                return redirect(goto)
            # Invalid password
            login_throttler.increment_attempts_counter(client_ip)
            msg = _("This admin password is not the right one. Only %(num)d attempts left.",
                    num=login_throttler.get_remaining_attempts(client_ip))
            form.errors['admin_password'] = [msg]
    return render_template("admin.html", form=form, admin_auth=True,
                           is_admin_auth_enabled=is_admin_auth_enabled)
Example #13
0
def login():
    # if get, render a login page, else verify
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        callback = request.form["next"]
        if isinstance(callback, str) and len(callback.strip()) == 0:
            callback = None

        crowd_session = CROWD_SERVER.get_session(username, password)
        if crowd_session:
            # logged in successfully, merge crowd JSON into session
            session.update(crowd_session)
            session["crowd_user"] = crowd_session["user"]["name"]
            app.logger.debug("User %s <%s> logged in.",
                             crowd_session["user"]["display-name"],
                             crowd_session["user"]["email"])
            return redirect(callback or url_for("index"))
        else:
            # failed
            app.logger.info("User %s unauthorized.", username)
            session["error"] = "Username or password incorrect!"
            return redirect(url_for("login", next=callback))
    else:
        # render a login page
        return render_template("login.html",
                               error=session.pop("error", ""),
                               next=request.args.get("next", ""))
Example #14
0
def login():
    # The request has to have an assertion for us to verify
    if 'assertion' not in request.form:
        abort(400)
 
    # Send the assertion to Mozilla's verifier service.
    data = {'assertion': request.form['assertion'], 'audience': app.config['SERVER']['host']}
    resp = requests.post('https://verifier.login.persona.org/verify', data=data, verify=True)
 
    # Did the verifier respond?
    if resp.ok:
        # Parse the response
        verification_data = json.loads(resp.content)
 
        # Check if the assertion was valid
        if verification_data['status'] == 'okay':
            # Log the user in by setting a secure session cookie
            session.update({'email': verification_data['email']})
            # Check for user in database, make user if not found
            user = User.query.filter_by(email=session['email']).first()
            if user is None:
                user = User(email=session['email'])
                db.session.add(user)
                db.session.commit()
            # Add user_id to session
            session['user_id'] = user.id
            return resp.content
 
    # Oops, something failed. Abort.
    abort(500)
Example #15
0
def login():
    if current_user is not None and current_user.is_authenticated() and login_fresh():
        return redirect_next()
    else:
        form = LoginForm(request.form)
        if request.method == 'POST' and form.validate():
            try:
                authenticate(username=form.email.data,
                             password=form.password.data)

                # Set session timeout
                session.permanent = True
                app.permanent_session_lifetime = app.config.get('SESSION_TIMEOUT', timedelta(minutes=30))

                flash('Welcome Back!', 'info')

                # Because shit can break
                session['_fresh'] = True
                session.update()
                if request.args.get('next'):
                    return redirect_next()
                else:
                    return redirect(url_for('user.profile'))
            except:
                app.logger.info('Invalid login attempt for username %s' % form.email.data)
                flash('Invalid username/password', 'error')
                return redirect(url_for('auth.login', next=request.args.get('next', '/')))

    context = {
        'title': 'Login',
        'description': 'Login form for BreezeMinder.com to access Breeze cards and MARTA reminders',
        'form': form
    }

    return render_template('auth/login.html', **context)
Example #16
0
def login():
    if request.method == "GET":
        return session['email'] if 'email' in session else "null"
    # The request has to have an assertion for us to verify
    if 'assertion' not in request.form:
        abort(400)

    # Send the assertion to Mozilla's verifier service.
    data = {'assertion': request.form['assertion'], 'audience': 'http://' + SERVER_IP + ':'+ str(PORT_NUMBER)}
    resp = requests.post('https://verifier.login.persona.org/verify', data=data, verify=True)

    # Did the verifier respond?
    if resp.ok:
        # Parse the response
        verification_data = json.loads(resp.content)

        # Check if the assertion was valid
        if verification_data['status'] == 'okay':
            # Log the user in by setting a secure session cookie
            session.update({'email': verification_data['email']})
            logging.debug('Login as: ' + verification_data['email'])
            return "Logged in as %s" % verification_data['email']

    logging.debug('Login failure: ' + str(resp))
    # Oops, something failed. Abort.
    abort(500)
Example #17
0
def login():
    """
    Login via Globus Auth.
    May be invoked in one of two scenarios:

      1. Login is starting, no state in Globus Auth yet
      2. Returning to application during login, already have short-lived
         code from Globus Auth to exchange for tokens, encoded in a query
         param
    """
    # the redirect URI, as a complete URI (not relative path)
    redirect_uri = url_for('login', _external=True)

    auth_client = load_app_client()
    auth_client.oauth2_start_flow(redirect_uri,
                                  requested_scopes='openid email profile')

    # If there's no "code" query string parameter, we're in this route
    # starting a Globus Auth login flow.
    # Redirect out to Globus Auth
    if 'code' not in request.args:
        auth_uri = auth_client.oauth2_get_authorize_url()

        # if there is a state parameter, pass it through without change
        if 'state' in request.args:
            auth_uri += '&state=' + request.args.get('state')

        return redirect(auth_uri)

    # If we do have a "code" param, we're coming back from Globus Auth
    # and can start the process of exchanging an auth code for a token.
    else:
        code = request.args.get('code')
        tokens_response = auth_client.oauth2_exchange_code_for_tokens(code)

        # Get the id_token (ids) that tells us who this user is (for the login/logout display)
        id_token = tokens_response.decode_id_token()

        # Get the Search API token (for authenticating Search API requests)
        auth_token_data = tokens_response.by_resource_server['auth.globus.org']
        AUTH_TOKEN = auth_token_data['access_token']

        # Set the initial page for the app
        initialpage = 'index'
        # If there is a state parameter, then it might be a hint to go to a specific page
        # in the interface when login completes. The name of the page will appear after
        # the prefix "goto-". E.g., "goto-index" or "goto-sessioninfo"
        if 'state' in request.args:
            loc = request.args.get('state').find("goto-")
            if loc == 0:
                initialpage = request.args.get('state')[5:]

        # Update the session cookie and go to the initial app page, determined above
        session.update(auth_token=AUTH_TOKEN,
                       id_token=id_token,
                       userid=id_token['sub'],
                       identity=id_token['preferred_username'],
                       fullname=id_token['name'],
                       is_authenticated=True)
        return redirect(url_for(initialpage))
Example #18
0
def select_geo():
    if not session.get('file'):
        return redirect(url_for('views.index'))
    context = {}
    if request.method == 'POST':
        inp = StringIO(session['file'])
        reader = UnicodeCSVReader(inp)
        header = reader.next()
        fields = {}
        geo_type = None
        valid = True
        if not request.form:
            valid = False
            context['errors'] = [
                'Select a field that contains a geography type'
            ]
        if valid:
            for k, v in request.form.items():
                if k.startswith("geotype"):
                    geo_type = v
                    index = int(k.split('_')[1])
                    fields[header[index]] = {
                        'geo_type': v,
                        'column_index': index
                    }
            mancer_data = get_data_sources(geo_type)
            session.update({'fields': fields, 'mancer_data': mancer_data})
            return redirect(url_for('views.select_tables'))
    return render_template('select_geo.html', **context)
Example #19
0
        def _auth_wrapper(*args, **kwargs):
            auth_result = check_auth(request=request,
                                     session=session,
                                     methods=methods)
            if not auth_result:
                return authenticate()

            user_fingerprint_sha1 = session.get('user_fingerprint_sha1', None)
            if user_fingerprint_sha1 is None:
                with WaptDB():
                    user = WaptUsers.get(name=auth_result['user'])
                user_fingerprint_sha1 = user.user_fingerprint_sha1

            user_acls = None
            if auth_result['auth_method'] == 'session':
                user_acls = session.get('user_acls', None)
            if user_acls is None:
                user_acls = get_user_acls(user_fingerprint_sha1)
            if require_any_of and not has_any_right(user_acls, require_any_of):
                return forbidden()
            logger.info(u'user %s authenticated' % auth_result)
            auth_result['user_acls'] = user_acls
            session.update(**auth_result)
            result = f(*args, **kwargs)
            return result
Example #20
0
    def _redirect(self):
        """Method!"""
        log.warn('-' * 80)
        log.warn('_redirect!')
        log.warn('-' * 80)
        log.warn(session)

        if ('state'
                not in session) or (request.args['state'] != session['state']):
            abort(500,
                  'Cross site request forgery or cookies not allowed/set?')

        data = {
            'grant_type': 'authorization_code',
            'code': request.args['code'],
            # I think this parameter is superfluous:
            # 'redirect_uri': f'https://{request.host}/smartonfhir/_redirect',
        }

        # session['token'] holds the endpoint where a token can be obtained.
        response = requests.post(session['token'], data)
        authorization_result = response.json()

        log.warn(authorization_result)

        session.update(authorization_result)

        params = self.__get_observations()
        qs = urlencode(params)

        redirect_url = f'https://{request.host}/app/{session["model"]}?{qs}'
        log.debug(f"Redirecting to '{redirect_url}'")
        log.debug('')

        return redirect(redirect_url)
Example #21
0
File: app.py Project: jqb1/ucs-db
def buy_it(car_id):
    print(car_id)
    new_balance = handle_buy(db, car_id, session['account']['id'])
    session['account']['balance'] = new_balance
    session.update()
    print(session['account'])
    return render_template('buy.html', account=session['account'])
Example #22
0
def login():
    # The request has to have an assertion for us to verify
    if 'assertion' not in request.form:
        abort(400)

    # Send the assertion to Mozilla's verifier service.
    data = {
        'assertion': request.form['assertion'],
        'audience': 'https://metaplace.paas.allizom.org/'
    }
    resp = requests.post('https://verifier.login.persona.org/verify',
                         data=data,
                         verify=True)

    # Did the verifier respond?
    if resp.ok:
        # Parse the response
        verification_data = json.loads(resp.content)

        # Check if the assertion was valid
        if verification_data['status'] == 'okay':
            # Log the user in by setting a secure session cookie
            session.update({
                'email':
                verification_data['email'],
                'mozillian':
                verification_data['email'] in local.MOZS
            })
            return 'You are logged in'

    abort(500)
Example #23
0
def login():
    if 'assertion' not in request.form:
        abort(400)

    # Send the assertion to Mozilla's verifier service.
    data = {'assertion': request.form['assertion'], 'audience': 'system.gaiamobile.org'}
    resp = requests.post('https://verifier.login.native-persona.org/verify', data=data, verify=True)
 
    # Did the verifier respond?
    if resp.ok:
        # Parse the response
        verification_data = json.loads(resp.content)
 
        # Check if the assertion was valid
        if verification_data['status'] == 'okay':
            # Log the user in by setting a secure session cookie
            session.update({'email': verification_data['email']})
            return verification_data['email']
        else:
            print 'status not okay', verification_data
    else:
        print 'resp.ok not true', resp
 
    # Oops, something failed. Abort.
    abort(500)
Example #24
0
def home():
    if 'current' not in session:
        #TODO: encrypt session so not readable
        game = new_game(8, 8, 10)
        session.update(game)

    return render_template('main/home.html', **session)
Example #25
0
def sso_lander_view(group):
    """
    Log a user into the system using a signed and encrypted get argument "token".

    Here a ttl of 60 seconds is life. See
    https://cryptography.io/en/latest/fernet/#cryptography.fernet.Fernet.decrypt.
    """
    secret = redis_cli.get('secret:{}'.format(group))
    if not secret:
        return 'group not found', 404
    fernet = Fernet(secret)

    token = request.args.get('token', '').encode('utf8')
    try:
        data = fernet.decrypt(token, ttl=60)
    except InvalidToken:
        return '403: Invalid Token', 403

    try:
        data = json.loads(data.decode('utf8'))
    except JSONDecodeError:
        return '400: problem parsing json', 400
    data['referrer'] = request.referrer
    session.update(
        profile=data,
        group=group,
    )

    group_key = 'info:{}'.format(group)
    redis_cli.lpush(
        group_key, '{nm} ({rt}) logged in at {dt:%Y-%m-%d %H:%M:%S}'.format(
            dt=datetime.now(), **data))
    return redirect('/')
Example #26
0
def login():
    if request.args.get('key') == open('secret.json', 'r').read():
        session.update({'msg': '', 'user': True})
        return redirect('/review')

    session.update({'msg': 'Not allowed', 'user': False})
    return redirect('/')
Example #27
0
def login():


    if 'assertion' not in request.form:
        abort(400)

    assertion_info = {'assertion': request.form['assertion'],
                        'audience': 'localhost:5000' } # window.location.host
    resp = requests.post('https://verifier.login.persona.org/verify',
                        data=assertion_info, verify=True)

    if not resp.ok:
        print 'Invalid response from remote verifier'
        abort(500)

    data = resp.json()

    if data['status'] == 'okay':
        session.update({'email': data['email']})
        email_key = get_email_ia(request.form['assertion'])
        value = app.config['CACHE'].get(email_key)

        value, flag = which_store(value, 'bia', request.form['assertion'])

        print 'storing under email'
        app.config['CACHE'].set(email_key, json.dumps(value))

        if flag:
          print 'storing under pgp key'
          pgp_key = value[0]['pgp']
          app.config['CACHE'].set(pgp_key, json.dumps(value))
        return resp.content
Example #28
0
def before_request():
    """Called before all requests. Initialize global template variables."""

    # Default template vars.
    g.info = rophako.utils.default_vars()

    # Default session vars.
    if not "login" in session:
        session.update(g.info["session"])

    # CSRF protection.
    if request.method == "POST":
        token = session.pop("_csrf", None)
        if not token or str(token) != str(request.form.get("token")):
            abort(403)

    # Refresh their login status from the DB.
    if session["login"]:
        import rophako.model.user as User
        if not User.exists(uid=session["uid"]):
            # Weird! Log them out.
            from rophako.modules.account import logout
            logout()
            return

        db = User.get_user(uid=session["uid"])
        session["username"] = db["username"]
        session["name"] = db["name"]
        session["role"] = db["role"]

    # Copy session params into g.info. The only people who should touch the
    # session are the login/out pages.
    for key in session:
        g.info["session"][key] = session[key]
Example #29
0
def login():
    next_url = request.args.get('next', url_for('.home'))
    if next_url == url_for(".login"):
        next_url = url_for(".home")

    # restirct redirect domain
    mo = P_LEGAL_NEXT_URL.match(next_url)
    if not mo:
        next_url = url_for(".home")

    if 'uid' in session:
        return redirect(next_url)

    if request.method == 'POST':
        username = request.form.get('username', '').strip()[:45]
        password = request.form.get('password', '').strip()
        recaptcha = request.form.get('g-recaptcha-response', '').strip()
        if len(username) == 0 or len(password) == 0:
            flash("Login information is incomplete!")
        elif len(recaptcha) == 0:
            flash("Missing reCAPTCHA token!")
        elif not check_recaptcha(app, recaptcha):
            flash("U r a robot?")
        else:
            db = BlogModel()
            user_data = db.login(username, password, request.remote_addr)
            if user_data is not None:
                session.update(user_data)
                return redirect(next_url)

            flash("Unable to log in using current information.")

    return render_template('login.html')
Example #30
0
def login() -> Union[str, None, werkzeug.wrappers.Response]:
    form = LoginForm()
    if request.method == 'GET':
        return render_template('home/login.html', form=form)
    else:
        if form.validate_on_submit() is True:  # 验证格式
            data = form.data
            user_field = User.query.filter_by(name=data['name']).first()
            if check_pwd(form) is True:  # 验证密码
                session.update({
                    'user': user_field.name,
                    'user_id': user_field.id
                })
                # 储存用户登录日志信息
                user_log = UserLog(
                    user_id=user_field.id,
                    ip=request.remote_addr,
                )
                db.session.add(user_log)
                db.session.commit()
                return redirect(
                    request.args.get('next') or url_for('home.user'))
            else:
                flash('密码验证失败', 'err')
        else:
            flash('用户名或密码格式不正确', 'err')
        return redirect(url_for('home.login'))
Example #31
0
def callback():
    current_app.logger.info('Handling authentication callback')

    code, state = _parse_auth_response()

    current_app.logger.info('Exchanging authz code for access and id tokens')

    id_token, access_token = _get_tokens(code, state)

    current_app.logger.info('Requesting userinfo')

    userinfo = _get_userinfo(id_token, state)

    session.update({
        'id_token': id_token.to_dict(),
        'id_token_jwt': id_token.to_jwt(),
        'access_token': access_token
    })

    if userinfo:
        current_app.provider.userinfo[id_token['sub']] = userinfo.to_dict()

    current_app.logger.info('Redirecting to {destination}'.format(
        destination=session.get('destination')))

    return redirect(session.pop('destination'))
Example #32
0
def login():
    # The request has to have an assertion for us to verify
    if 'assertion' not in request.form:
        abort(400)

    # Send the assertion to Mozilla's verifier service.
    data = {'assertion': request.form['assertion'], 'audience': app.config['audience']}
    resp = requests.post('https://verifier.login.persona.org/verify', data=data, verify=True)

    # Did the verifier respond?
    if resp.ok:
        # Parse the response
        verification_data = json.loads(resp.content)

        # Check if the assertion was valid
        if verification_data['status'] == 'okay':
            # Check if current user exists
            u = User.find_one({'email': verification_data['email']})

            # If it's a new user, create it
            if not u:
                email = verification_data['email'].strip().lower()
                u = User({'email': email,
                          'created_at': int(time()), 'meta': {},
                          'gravatar_hash': md5(email),
                          'credentials': {}})
                u.save()

            session['user_id'] = str(u._id)

            session.update({'email': verification_data['email']})
            return ""

    # Oops, something failed. Abort.
    abort(500)
Example #33
0
def login():
    """ Confirm that a username and password match a User record in the db. """
    username = request.args.get('username')
    password = request.args.get('password')

    success = False
    message = ''

    if username and password:
        user_match = db.session.query(User)\
                               .filter(User.username == username).first()
        if user_match and sha256_crypt.verify(password, user_match.password):
            if user_match.active:
                session.update({
                    'username': user_match.username,
                    'userId': user_match.id,
                    'loggedIn': True
                })
                success = True
            else:
                message = 'Please confirm your registration before logging in'
        else:
            message = 'Login credentials invalid'
    else:
        message = 'You must provide a username and password'

    return jsonify(success=success, message=message)
Example #34
0
def callback():
    """Handles the interaction with Globus Auth."""
    # If we're coming back from Globus Auth in an error state, the error
    # will be in the "error" query string parameter.
    if 'error' in request.args:
        flash("You could not be logged into the portal: " +
              request.args.get('error_description', request.args['error']))
        return redirect(url_for('home'))

    # Set up our Globus Auth/OAuth2 state
    redirect_uri = url_for('callback', _external=True)

    client = _load_dlhub_client()
    client.oauth2_start_flow(redirect_uri, refresh_tokens=False)

    # If there's no "code" query string parameter, we're in this route
    # starting a Globus Auth login flow.
    if 'code' not in request.args:
        # TODO (lw): Should this be used?
        # additional_authorize_params = (
        #    {'signup': 1} if request.args.get('signup') else {})

        auth_uri = client.oauth2_get_authorize_url()
        return redirect(auth_uri)
    else:
        # If we do have a "code" param, we're coming back from Globus Auth
        # and can start the process of exchanging an auth code for a token.
        code = request.args.get('code')
        tokens = client.oauth2_exchange_code_for_tokens(code)
        # id_token = tokens.decode_id_token(client)
        session.update(tokens=tokens.by_resource_server, is_authenticated=True)

        return redirect(url_for('home'))
Example #35
0
 def log_in(self):
     user_session.update(
         {
             'email_address': self.email_address,
             'current_role': self.get_roles()[0],
             }
         )
Example #36
0
 def get():
     args = request.args
     params_valid = ('phone', 'name', 'course_id')
     missing_msg = [x for x in params_valid if x not in args]
     student_id = args.get('id')
     if len(missing_msg) > 0 and not student_id:
         return jsonify({
             "code": 0,
             "msg": "missing params: " + str(missing_msg)
         })
     phone = args.get('phone')
     name = args.get('name')
     course_id = args.get('course_id')
     rule = [
         Student.phone == phone, Student.course_id == course_id,
         Student.name == name
     ]
     if student_id:
         rule = [Student.id == student_id]
     column = list(Student.__table__.c)
     column.extend([
         Course.start_time, Course.end_time,
         Subject.name.label('course_name')
     ])
     data = Student.query.with_entities(*column).join(Course, Student.course_id == Course.id)\
         .join(Subject, Course.subject_id == Subject.id)\
         .filter(*rule).first()
     if data:
         session.update({"student_id": data.id})
         return jsonify({"code": 1, "msg": "查询成功", "data": data})
     return jsonify({"code": 0, "msg": "找不到相关学员信息", "data": []})
Example #37
0
def select_geo():
    if not session.get('file'):
        return redirect(url_for('views.index'))
    context = {}
    if request.method == 'POST':
        inp = StringIO(session['file'])
        reader = UnicodeCSVReader(inp)
        header = reader.next()
        fields = {}
        geo_type = None
        valid = True
        if not request.form:
            valid = False
            context['errors'] = ['Select a field that contains a geography type']
        if valid:
            for k,v in request.form.items():
                if k.startswith("geotype"):
                    geo_type = v
                    index = int(k.split('_')[1])
                    fields[header[index]] = {
                        'geo_type': v,
                        'column_index': index
                    }
            mancer_data = get_data_sources(geo_type)
            session.update({'fields': fields, 'mancer_data': mancer_data})
            return redirect(url_for('views.select_tables'))
    return render_template('select_geo.html', **context)
Example #38
0
def admin():
    """Admin authentication.

    When ADMIN_PASSWORD is empty, admin authentication is deactivated.
    """
    form = AdminAuthenticationForm()
    goto = request.args.get('goto', url_for('.home'))
    is_admin_auth_enabled = bool(current_app.config['ADMIN_PASSWORD'])
    if request.method == "POST":
        client_ip = request.remote_addr
        if not login_throttler.is_login_allowed(client_ip):
            msg = _("Too many failed login attempts, please retry later.")
            form.errors['admin_password'] = [msg]
            return render_template("admin.html", form=form, admin_auth=True,
                                   is_admin_auth_enabled=is_admin_auth_enabled)
        if form.validate():
            # Valid password
            if (check_password_hash(current_app.config['ADMIN_PASSWORD'],
                                    form.admin_password.data)):
                session['is_admin'] = True
                session.update()
                login_throttler.reset(client_ip)
                return redirect(goto)
            # Invalid password
            login_throttler.increment_attempts_counter(client_ip)
            msg = _("This admin password is not the right one. Only %(num)d attempts left.",
                    num=login_throttler.get_remaining_attempts(client_ip))
            form.errors['admin_password'] = [msg]
    return render_template("admin.html", form=form, admin_auth=True,
                           is_admin_auth_enabled=is_admin_auth_enabled)
Example #39
0
def logout():
    """
    Logout request handler
    """
    session.update(authenticated=False, username=None)

    return redirect(url_for("content.login"))
Example #40
0
def login():
    # The request has to have an assertion for us to verify
    if 'assertion' not in request.form:
        abort(400)

    # Send the assertion to Mozilla's verifier service.
    data = {'assertion': request.form['assertion'],
            'audience': 'https://metaplace.paas.allizom.org/'}
    resp = requests.post('https://verifier.login.persona.org/verify',
                         data=data, verify=True)

    # Did the verifier respond?
    if resp.ok:
        # Parse the response
        verification_data = json.loads(resp.content)

        # Check if the assertion was valid
        if verification_data['status'] == 'okay':
            # Log the user in by setting a secure session cookie
            session.update({
                'email': verification_data['email'],
                'mozillian': verification_data['email'] in local.MOZS
            })
            return 'You are logged in'

    abort(500)
def test_user_has_a_valid_role(test_session):
    with app.test_request_context("/"):
        session.update(test_session)
        assert not user_has_a_valid_role(["admin-full"])
        assert user_has_a_valid_role(["standard-download"])
        assert not user_has_a_valid_role(["admin-power", "admin-full"])
        assert user_has_a_valid_role(["standard-upload", "standard-download"])
Example #42
0
def impersonate(uid):
    """Impersonate a user."""
    # Check that they exist.
    if not User.exists(uid=uid):
        flash("That user ID wasn't found.")
        return redirect(url_for(".users"))

    db = User.get_user(uid=uid)
    if db["role"] == "deleted":
        flash("That user was deleted!")
        return redirect(url_for(".users"))

    # Log them in!
    orig_uid = session["uid"]
    session.update(
        login=True,
        uid=uid,
        username=db["username"],
        name=db["name"],
        role=db["role"],
        impersonator=orig_uid,
    )

    flash("Now logged in as {}".format(db["name"]))
    return redirect(url_for("index"))
Example #43
0
def complete_2fa():
    session.update(step='complete-2FA', code=request.form.get('code'))
    # print(session)

    resp = make_response('ret=1,redir=/remote/fortisslvpn_xml')
    resp.set_cookie('SVPNCOOKIE', cookify(dict(session)))
    return resp
Example #44
0
def oauth_save():
    # This will store it in the cookie. If someone wants to do the whole
    # 3 legged oauth dance, pull requests welcome.
    session.update({'oauth': {
        'key': request.form.get('key'),
        'secret': request.form.get('secret')}
    })
    return redirect('/')
Example #45
0
def login():
    if not 'user_id' in session:
        session.update(
                g.twitter.get_authentication_tokens(callback_url=app.config['CALLBACK_URL'])
        )

        return redirect(session['auth_url'])
    return redirect(url_for('index'))
Example #46
0
def settings(page=None):
    if not session.get("uid"):
        return redirect(url_for("signin", next=get_path(request)))

    if page not in ("identity", "regional", "password"):
        return redirect(url_for("settings", page="identity"))

    if request.method == "POST":
        if request.form.get("validate"):
            if page == "password":
                backend = UserBackend()

                if not backend.authenticate(session.get("login"), request.form.get("password-current")):
                    flash(_("Current password is invalid."), "error")
                elif request.form.get("password-new") != request.form.get("password-repeat"):
                    flash(_("Passwords don't match."), "error")
                else:
                    try:
                        backend.set(modify=True, login=session.get("login"), password=request.form.get("password-new"))
                        flash(_("Password successfuly changed."), "info")
                    except PasswordTooShort:
                        flash(
                            _(
                                "Password is too short. Must be a least %(length)d characters long.",
                                length=PASSWORD_MIN_LENGTH,
                            ),
                            "error",
                        )
            else:
                settings = dict((x, request.form.get(x)) for x in SETTINGS_LIST if x in request.form)

                if settings:
                    user = UserBackend().set(modify=True, login=session.get("login"), **settings)

                    session.update(
                        {
                            "name": user.fullname,
                            "avatar": "//gravatar.com/avatar/%s" % hashlib.md5(user.email.lower()).hexdigest(),
                        }
                    )

                    if "locale" in settings:
                        g.user.locale = settings.get("locale")

                    flash(_("Settings successfuly saved."), "info")

        return redirect(url_for("settings", page=page))

    locales = [(x.language, x.display_name.capitalize()) for x in app.babel_instance.list_translations()]

    return render_template(
        "settings.html",
        page=page,
        locales=locales,
        timezones=common_timezones,
        current_locale=get_locale().language,
        current_timezone=get_timezone().zone,
    )
Example #47
0
def login():
    if request.method == 'POST':
        codename = request.form['codename']
        if valid_codename(codename):
            session.update(codename=codename, logged_in=True)
            return redirect(url_for('lookup'))
        else:
            flash("Sorry, that is not a recognized codename.", "error")
    return render_template('login.html')
Example #48
0
    def _getAnswer(self):
        try:
            entry = session.pop('login_as_orig_user')
        except KeyError:
            raise NoReportError(_('No login-as history entry found'))

        session.user = User.get(entry['user_id'])
        session.update(entry['session_data'])
        return True
Example #49
0
def get_authorize_url(callback_args={}):
    # Username is stored in oauth callback as url arg
    
    request_token = g.dropbox.obtain_request_token()
    session.update(request_token=request_token.to_string())
    
    callback_args.update(_external=True)
    callback = url_for('frontend.oauth_callback', **callback_args)
    return g.dropbox.build_authorize_url(request_token, callback)
Example #50
0
def reg_user_by_form():
    '''
    @todo:注册用户
    '''
    res = reg_user(form2dic(request.form)) 
    if res:
        session.update(set_user_session({}, res))
        return redirect('/')
    else:
       return render_template('info.html', info=u"服务器错误")
Example #51
0
def login():
    data = request.json
    current_user = user.get_user_by_email(data.get("email"))
    if not current_user:
        return message("User is not found.", 404)
    if not current_user.password == encrypt(data.get("password")):
        return message("Password is not correct.", 401)
    session["is_login"] = True
    session.update(current_user.dict())
    return jsonify(**current_user.dict()), 200    
Example #52
0
 def switch_current_role(self, role):
     if role in self.get_roles():
         user_session.update(
             {
                 'current_role': role
                 }
             )
         return True
     else:
         return False
Example #53
0
def update_user_action():
    _id = session.get('_id', None)
    if _id:
        user = form2dic(request.form)
        user.pop('password')
        user = update_user(_id, user)
        session.clear()
        session.update(set_user_session({}, user))
        return redirect('/')  
    else:
        return redirect('/')       
Example #54
0
def login():
	if request.method == 'POST':
		query = "SELECT %s FROM users where username='******' and password='******'" % (",".join(attributes), request.form['username'], request.form['password'])
		cur = mysql.get_db().cursor()
		cur.execute(query)
		data = cur.fetchone()
		if data:
			session.update(zip(attributes, data))
			return redirect(url_for('home'))
		
	return '''
Example #55
0
    def put(self, id):
        data, status = request.json or abort(400), 202
        validation = t.Dict({'email': t.Email, 'password':
            t.String}).ignore_extra('*').append(self._authenticate)
        try:
            validation.check(data)
            response = dict(session)
        except t.DataError as e:
            response, status = e.as_dict(), 404
            session.update({'is_anonymous': True})

        return jsonify(response, status=status)
Example #56
0
    def __set_checkout(self, amount, payment_details):
        """ When a customer is ready to check out, use the SetExpressCheckout
            call to specify the amount of payment, return URL, and cancel
            URL. The SetExpressCheckout response contains a token for use in
            subsequent steps.
            Step 2 contained. Redirect the Customer to PayPal for
            Authorization.
        """
        session.update(payment_details)

        request_params = {
            'METHOD': SET_CHECKOUT,
            'NOSHIPPING': 1,
            'REQCONFIRMSHIPPING': 0,
            # FIXME: BuildError
            'RETURNURL': url_for('payment.process_payment',
                                 payment_method=self.method_name,
                                 _external=True),
            'CANCELURL': url_for('payment.cancel_payment',
                                 payment_method=self.method_name,
                                 _external=True)
        }
        # include description for items added to cart
        try:
            request_params.update(self.__prepare_cart_items())
        except AttributeError:
            sentry.captureException()
            return {
                'action': 'redirect',
                'target': url_for('payment.error_payment',
                                  payment_method=self.method_name,
                                  _external=True)
            }

        response = self.__do_request(request_params)
        if response['ACK'] in RESPONSE_OK:
            self.order.set_payment_details(token=response['TOKEN'])
            webface_url = self.__get_redirect_url(response)
            response = self.order.as_dict()
            response.update({
                'action': 'redirect',
                'target': webface_url
            })
            return jsonify_status_code(response)

        return {
            'action': 'redirect',
            'target': url_for('payment.error_payment',
                              payment_method=self.method_name,
                              _external=True)
        }
Example #57
0
    def decorated_function(*args, **kwargs):
        url = request.url

        # for testing
        if 'FAKE_AUTH' in current_app.config:
            session.update(current_app.config['FAKE_AUTH'])
        if request.args.get('force_login'):
            del session['token']
            url = re.sub(r'[?&]force_login=[^&]+', '', url)

        if 'token' not in session:
            return redirect(url_for('login', next=url))
        else:
            return f(*args, **kwargs)
Example #58
0
def undo_impersonate_user():
    """Undo an admin impersonation login and revert to the old user"""
    from indico.modules.auth import logger
    from indico.modules.users import User

    try:
        entry = session.pop('login_as_orig_user')
    except KeyError:
        # The user probably already switched back from another tab
        return
    user = User.get_one(entry['user_id'])
    logger.info('Admin %r stopped impersonating user %r', user, session.user)
    session.user = user
    session.update(entry['session_data'])