コード例 #1
0
ファイル: security.py プロジェクト: SzkolaCzytania/szcz.app
def velruse_complete(context, request):
    email = context.profile.get('verifiedEmail')
    user = DBSession.query(User).get(email)

    if not user:
        session = DBSession()
        try:
            given_name, family_name = context.profile['displayName'].split(' ')
        except ValueError:
            given_name = context.profile['displayName']
            family_name = context.profile['displayName']
        user = User(given_name=given_name,
                    family_name=family_name,
                    email=context.profile.get('verifiedEmail'))
        session.add(user)
        headers = remember(request, user.email)
        request.session.flash({'title': u'Zarejestrowany',
                               'body': u'Witamy w Szkole Czytania. Twoje konto zostało utworzone.'},
                               queue='success')
        return HTTPFound(location='/profile', headers=headers)

    request.session.flash({'title': u'Zalogowany',
                           'body': u'Witamy w Szkole Czytania!'},
                           queue='success')
    headers = remember(request, user.email)
    return HTTPFound(location='/', headers=headers)
コード例 #2
0
ファイル: login_views.py プロジェクト: kratenko/gy
def view_login(request):
    """
    View for login form and logging in.
    """
    failed = False
    reason = None
    if request.POST:
        # login request submitted:
        name = request.POST.getone('name')
        password = request.POST.getone('password')
        try:
            user = DBSession.query(User).filter_by(name=name).one()
        except NoResultFound:
            failed = True
            reason = u'That password is not correct for that user.'
        else:
            if user.check_password(password):
                # password correct, log in user for this session:
                security.remember(request, user)
                raise HTTPFound('/')
            else:
                failed = True
                reason = u'That password is not correct for that user.'
    return {
        'Title': 'Login',
        'failed': failed,
        'reason': reason,
    }
コード例 #3
0
ファイル: user.py プロジェクト: VictorMedeiros/LBGenerator
    def authenticate(self):
        """
        The token endpoint is used by the client to obtain an access token by
        presenting its authorization grant or refresh token. The token
        endpoint is used with every authorization grant except for the
        implicit grant type (since an access token is issued directly).
        """
        user = self.request.params.get('nm_user')
        passwd = self.request.params.get('passwd_user')

        if user is None:
            raise Exception('Required parameter nm_user not found in the request')
        elif passwd is None:
            raise Exception("Required parameter 'passwd_user' not found in the request")

        if user == config.ADMIN_USER and passwd == config.ADMIN_PASSWD:
            headers = remember(self.request, user)
            return Response('OK', headers=headers)

        member = self.context.get_member(user)
        if not member:
            raise Exception('No such User!')

        if member.passwd_user != passwd:
            raise Exception('Invalid Password!')

        headers = remember(self.request, user)
        return Response('OK', headers=headers)
コード例 #4
0
ファイル: auth.py プロジェクト: France-ioi/alkindi-backend
def oauth_callback_view(request):
    # This view handles the outcome of authentication performed by the
    # identity provider.
    error = request.params.get('error')
    if error is not None:
        message = format_error_value(request.params)
        return {'error': message}
    try:
        accept_oauth2_code(request)
    except AuthenticationError as ex:
        return {'error': str(ex)}
    # Get the user identity (refreshing the token should not be needed).
    profile = get_user_profile(request, refresh=False)
    # Make pyramid remember the user's id.
    user_id = find_user_by_foreign_id(request.db, profile['idUser'])
    if user_id is None:
        user_id = import_user(request.db, profile, now=datetime.utcnow())
    else:
        update_user(request.db, user_id, profile)
    request.db.commit()
    # Clear the user's cached principals to force them to be refreshed.
    reset_user_principals(request)
    remember(request, str(user_id))
    # The view template posts the result (encoded as JSON) to the parent
    # window, causing the frontend to update its state.
    # The Origin header is passed to the template to limit recipients.
    # Pass the CSRF token to the login window so that it can send it to
    # the front.
    return {
        'user_id': user_id,
        'csrf_token': request.session.get_csrf_token(),
        'origin': request.headers.get('Origin')
    }
コード例 #5
0
ファイル: credentials.py プロジェクト: EasyPost/pyshop
    def render(self):

        login_url = resource_url(self.request.context, self.request, 'login')
        referrer = self.request.url
        # never use the login form itself as came_from
        if referrer == login_url:
            referrer = '/'
        came_from = self.request.params.get('came_from', referrer)
        login = self.request.params.get('user.login', '')
        if 'form.submitted' in self.request.params:
            password = self.request.params.get('user.password', u'')
            if password:
                if User.by_ldap_credentials(
                        self.session, login, password,
                        self.request.registry.settings) is not None:
                    log.info('login %r succeed', login)
                    headers = remember(self.request, login)
                    return HTTPFound(location=came_from,
                                     headers=headers)
 
                if User.by_credentials(
                        self.session, login, password) is not None:
                    log.info('login %r succeed', login)
                    headers = remember(self.request, login)
                    return HTTPFound(location=came_from,
                                     headers=headers)

        return {'came_from': came_from,
                'user': User(login=login),
                }
コード例 #6
0
    def callback(self):
        """Receive an authorization code and log in the user.
        """
        request = self.request
        code = request.params.get('code')
        state = request.params.get('state')
        if not code or not state:
            return HTTPBadRequest("Missing code or state parameters")

        session = request.session
        session_state = session.get(self.session_prefix + 'state')
        if session_state != state:
            # CSRF protection
            return HTTPBadRequest(body="Incorrect state value")

        self.prepare_access_token(code)

        userid = self.get_userid()
        if userid:
            remember(request, userid)

        location = session.get(self.session_prefix + 'came_from')
        if not location:
            location = request.application_url
        headers = [('Cache-Control', 'no-cache')]
        return HTTPFound(location=location, headers=headers)
コード例 #7
0
ファイル: account.py プロジェクト: MSPARP/logcabin
def verify_email(request):
    try:
        user_id = int(request.GET["user_id"].strip())
        email_address = request.GET["email_address"].strip()
        token = request.GET["token"].strip()
    except (KeyError, ValueError):
        raise HTTPNotFound
    stored_token = request.session.redis.get("verify:%s:%s" % (user_id, email_address))
    if not user_id or not email_address or not token or not stored_token:
        raise HTTPNotFound

    stored_token = stored_token.decode("utf-8")

    if not stored_token == token:
        raise HTTPNotFound

    if (
        request.db.query(func.count("*")).select_from(User)
        .filter(func.lower(User.email_address) == email_address.lower()).scalar()
    ):
        request.session.flash("There's already an account with that email address.")
        return HTTPFound(request.route_path("home"))

    try:
        user = request.db.query(User).filter(User.id == user_id).one()
    except NoResultFound:
        raise HTTPNotFound

    user.email_address = email_address
    user.email_verified = True

    remember(request, user.id)
    request.session.flash("Your email address has been verified.")

    return HTTPFound(request.route_path("home"))
コード例 #8
0
ファイル: views.py プロジェクト: WickyYao/chat
def login_ajax(request):
    if request.POST.get('login'):
        username = request.POST.get('username')
        password = request.POST.get('password')

        user_data = user.find_one({"username":username})
        if user_data and user_data['password'] == password:
            user_id = user_data['_id']
            headers = remember(request, str(user_id))
            return HTTPFound(location=request.route_url('public_room'),
                             headers=headers)
        else:
            return False

    if request.POST.get('signup'):
        username = request.POST.get('username')
        password = request.POST.get('password')

        user_data = user.find_one({"username":username})
        if user_data and user_data['username'] == username:
            return False
        else:
            user_data = {'username':username, 'password':password,\
                    'nickname':username, 'textcolor':'#000000'}
            user_id = user.insert(user_data)
            headers = remember(request, str(user_id))
            return HTTPFound(location=request.route_url('public_room'),
                             headers=headers)
コード例 #9
0
ファイル: views.py プロジェクト: attakei/esauth
 def post(self):
     form = self.get_form()
     if not form.validate():
         return self.response
     security.remember(self.request, 'admin_user')
     redirect_url = self.request.params.get('next') or '/'
     return HTTPFound(redirect_url)
コード例 #10
0
def login_post(request):  # tested
    next = request.params.get('next') or request.route_url('home')
    login = request.POST.get('login', '')
    password = request.POST.get('password', '')
    # print(login)
    log.debug(login)
    user = DBSession.query(User).filter_by(login=login).first()
    if user and user.check_password(password):
        client = Client(user_id=user.id)
        user.clients.append(client)
        DBSession.add(client)
        DBSession.flush()
        headers = remember(request, principal=client.id)
        response = Response()
        response.headers = headers
        locale_id = user.default_locale_id
        if not locale_id:
            locale_id = 1
        response.set_cookie(key='locale_id', value=str(locale_id))
        response.set_cookie(key='client_id', value=str(client.id))
        headers = remember(request, principal=client.id)
        # return HTTPFound(location=next, headers=response.headers)
        return HTTPOk(headers=response.headers, json_body={})
        # return {}
    return HTTPUnauthorized(location=request.route_url('login'))
コード例 #11
0
ファイル: views.py プロジェクト: annndrey/simplesite
def client_oauth_register(request, regdict):
	nxt = request.route_url('main')
	loc = get_localizer(request)
	headers = None
	cfg = request.registry.settings
	mailer = get_mailer(request)
	errors = {}
	sess = DBSession()

	login = regdict.get('username', None)
	passwd = regdict.get('password', None)
	email = regdict.get('email', None)
	name_family = regdict.get('familyname', '')
	name_given = regdict.get('givenname', '')


	if login is not None and passwd is not None:
		q = sess.query(User).filter(User.name == login)
		logincount = q.count()
		if logincount == 1:
			if q is not None:
				for user in q:
					if user.password == passwd and user.name == login:
						headers = remember(request, login)
						return headers
					else:
						request.session.flash({
								'class' : 'warning',
								'text'  : request.translate(_('Пользователь с таким именем уже есть. Мы не знаем что вам делать'))
								})
						return False
						
		else:
			if headers is None:
				try:
					usr = User(login, passwd)
					usr.email = email
					usr.admin = 0
					sess.add(usr)
					#email user credentials to a given email
					sess.flush()
					headers = remember(request, login)
					message = Message(subject=request.translate(_("Новая учетная запись на lietlahti-park.ru")),
									  sender="*****@*****.**",
									  recipients=[email,],
									  body="{0}: login - {1}, password - {2}".format(request.translate(_("Добро пожаловать на наш сайт, надеемся, что вам тут понравится. Ваши учетные данные")), login, passwd))
					mailer.send(message)
					transaction.commit()
					return headers

				except IntegrityError:
					sess.rollback()
					request.session.flash({
							'class' : 'warning',
							'text'  : request.translate(_('Пользователь с таким именем уже есть. Мы работаем над этой проблемой :('))
							})
					return False

	else:
		return False
コード例 #12
0
ファイル: views.py プロジェクト: BairnOwl/YHack
def login(request):
    login_url = request.route_url('login')
    referrer = request.url
    if referrer == login_url:
        referrer = '/'
    came_from = request.params.get('came_from', referrer)
    message = ''
    login = ''
    if 'form.submitted' in request.params:
        login = request.params['login']
        user = request.db.get_user(login)
        if user is None: # new account
            if 'facebook_id' in request.params: # TODO: check if existing user w/ same facebook_id
                user = User(dict(
                    facebook_id = int(request.params['facebook_id']),
                    username = login,
                    name = request.params['name'],
                    interests = []
                ))
                request.db.insert_user(user)
                headers = remember(request, login)
                request.session['user'] = user
                return HTTPFound(location = came_from, headers = headers)
        else:
            if 'facebook_id' in request.params and user.facebook_id == int(request.params['facebook_id']):
                headers = remember(request, login)
                request.session['user'] = user
                return HTTPFound(location = came_from, headers = headers)
            else:
                message = 'Mismatch with Facebook'

    return dict(message = message, url = request.application_url + '/login', came_from = came_from, login = login)
コード例 #13
0
ファイル: views.py プロジェクト: strazdas/task_tracker
def login(request):
    message = None
    form = Form(request, schema=UserSchema())
    if request.method == 'POST' and form.validate():
        username = request.params['username']
        password = request.params['password']
        password_again = request.params['password_again']

        if bool(password_again):
            if password == password_again:
                user = form.bind(User())
                DBSession.add(user)
                DBSession.flush()
                user_id = user.id
                headers = remember(request, user.id)
                return HTTPFound(location='/', headers=headers)
            else:
                message = 'Passwords do not match.'
        else:
            user = DBSession.query(User).filter(User.username==username).first()
            if user and user.password == password:
                headers = remember(request, user.id)
                return HTTPFound(location='/', headers=headers)
            else:
                message = 'Username or password is incorrect.'
    return {
        'message': message,
        'form': form,
        'renderer': FormRenderer(form),
        'user': get_user(request),
    }
コード例 #14
0
ファイル: views.py プロジェクト: frostpeng/frostcms
def api_user_login(request):
    """用户登录api验证
          传入:username,password
   返回:code为1 成功,0失败
    """
    name, password,remember_value = [request.params.get(x, '').strip() for x in\
                                ['username', 'password','remember']]
    conn = DBSession()
    user = conn.query(User).filter(User.name==name).first()
    if user:
        if user.role==1:
            mentor=conn.query(Mentor).filter(Mentor.userid==user.id).first()
            if mentor and mentor.state==1:
                return dict(code=201,error=u'账号已经锁定,请联系管理员')
        elif user.role==2:
            student=conn.query(Student).filter(Student.userid==user.id).first()
            if student and student.state==1:
                return dict(code=201,error=u'账号已经锁定,请联系管理员')
        if user.password == md5(password):
            user.lastlogin=time.time()
            conn.flush()
            if remember_value=='true':
                expire_in = time.time()+7*24*60*60
                headers = remember(request, user.id,max_age=expire_in)
            else:
                headers=remember(request, user.id)
            request.response_headerlist=headers
            return dict(return_url="/public/lesson_list")
        return dict(code=202,error=u'用户名密码不匹配')
    return dict(code=203,error=u'用户不存在')
コード例 #15
0
def login_cheat(request):  # TODO: test
    next = request.params.get('next') or request.route_url('dashboard')
    login = request.json_body.get('login', '')
    passwordhash = request.json_body.get('passwordhash', '')
    log.debug("Logging in with cheat method:" + login)
    user = DBSession.query(User).filter_by(login=login).first()
    if user and user.password.hash == passwordhash:
        log.debug("Login successful")
        client = Client(user_id=user.id)
        user.clients.append(client)
        DBSession.add(client)
        DBSession.flush()
        headers = remember(request, principal=client.id)
        response = Response()
        response.headers = headers
        locale_id = user.default_locale_id
        if not locale_id:
            locale_id = 1
        response.set_cookie(key='locale_id', value=str(locale_id))
        response.set_cookie(key='client_id', value=str(client.id))
        headers = remember(request, principal=client.id)
        return response

    log.debug("Login unsuccessful for " + login)
    return HTTPUnauthorized(location=request.route_url('login'))
コード例 #16
0
ファイル: auth.py プロジェクト: CroissanceCommune/autonomie
def connect_user(request, form_datas):
    """
    Effectively connect the user

    :param obj request: The pyramid Request object
    :pram dict form_datas: Validated form_datas
    """
    login = form_datas['login']
    login_id = Login.id_from_login(login)
    log.info(
        u" + '{0}' id : {1} has been authenticated".format(
            login, login_id
        )
    )
    # Storing the form_datas in the request object
    remember(request, login)
    remember_me = form_datas.get('remember_me', False)
    if remember_me:
        log.info("  * The user wants to be remembered")
        longtimeout = get_longtimeout()
        request.response.set_cookie(
            'remember_me',
            "ok",
            max_age=longtimeout,
        )
コード例 #17
0
    def __call__(self):
        if self.request.user is not None:
            return self.success_response()

        form = _get_login_form(self.request, use_ajax=self.request.is_xhr)

        if 'submit' in self.request.params:
            controls = self.request.params.items()
            log.info(u"Authenticating : '{0}'".format(
                self.request.params.get('login'))
            )

            try:
                datas = form.validate(controls)
            except ValidationFailure, err:
                log.exception(u" - Authentication error")
                err_form = err.render()
                result = self.response(err_form, failed=True)

            else:
                login = datas['login']
                log.info(u" + '{0}' has been authenticated".format(login))
                # Storing the datas in the request object
                remember(self.request, login)
                remember_me = datas.get('remember_me', False)
                if remember_me:
                    log.info("  * The user wants to be remembered")
                    longtimeout = get_longtimeout()
                    self.request.response.set_cookie(
                        'remember_me',
                        "ok",
                        max_age=longtimeout,
                    )
                result = self.success_response()
コード例 #18
0
ファイル: security.py プロジェクト: NaturalSolutions/NsPortal
def login(request):
    user_id = request.POST.get('userId', '')
    pwd = request.POST.get('password', '')
    user = DBSession.query(User).filter(User.id==user_id).one()
    if user is not None and user.check_password(pwd):
        table = Base.metadata.tables['VAllUsersApplications']
        query = select([
            table
        ]).where((table.c['TSit_Name'] == dbConfig['siteName']) & (table.c['TUse_PK_ID'] == user_id) & (table.c['TRol_Label'] != 'Interdit')).order_by(table.c['TIns_Order'])
        result = DBSession.execute(query).fetchall()
        claims = {
            "iss": user_id,
            "sub": user_id,
            "username": user.Login,
            "userlanguage": user.Language,
            "roles" : {
                row.TIns_Label : row.TRol_Label for row in result
            }
        }
            
        jwt = make_jwt(request, claims)
        response = Response(body='login success', content_type='text/plain')
        remember(response, jwt)
        transaction.commit()
        return response
    else:
        transaction.commit()
        return HTTPUnauthorized()
コード例 #19
0
ファイル: permissions.py プロジェクト: System25/gecoscc-ui
 def __acl__(self):
     # Get the remote address
     remote_addr = self.request.remote_addr
     header = 'remote_addr'
     if 'X-Real-IP' in self.request.headers:
         remote_addr = self.request.headers['X-Real-IP']
         header = 'X-Real-IP'
     if 'X-Forwarded-For' in self.request.headers:
         remote_addr = self.request.headers['X-Forwarded-For']
         header = 'X-Forwarded-For'
     
     logger.debug('InternalAccessFactory: remote_addr=%s header=%s (%s)'%(remote_addr, header, str(self.request.headers.items())))
     
     # Check if the remote IP address is localhost
     if remote_addr == '127.0.0.1' or remote_addr == '::1':
         logger.debug('InternalAccessFactory: access allowed for localhost: %s'%(remote_addr))
         remember(self.request, 'localhost_access')
         return  [(Allow, Everyone, 'view')]
     
     server_list = self.request.db.servers.find()
     
     # Check if the remote IP address belongs to a GECOSCC server
     for server in server_list:
         if server['address'] == remote_addr:
             logger.debug('InternalAccessFactory: access allowed for GECOS CC server: %s'%(server['name']))
             remember(self.request, server['name'])
             return [(Allow, Everyone, 'view')]      
             
     logger.debug('InternalAccessFactory: forbidden access for %s'%(remote_addr))
     raise HTTPForbidden('Internal access only')
コード例 #20
0
ファイル: views.py プロジェクト: raxitcholera/pyramid
def login_view(request):
    if request.method == 'POST' or 'logged_session_id' in request.session:
        if request.POST.get('UserName') and request.POST.get('Password'):
            passw=set_password(request.POST.get('Password'))
            usr=DBSession.query(Users).filter_by(name=request.POST['UserName'],password=passw).first()
            if usr:
                request.session.flash('Welcome!')
                
                request.session['logged_in']='yes'
                #request.session['logged_in_id']=usr.id
                #request.session['logged_in_group']=usr.group
                
                
                Sessiontimeoutime=datetime.now() + timedelta(minutes = 10)
                newSessionObj = Login_Session(userid=usr.id,group=usr.group,timeout=Sessiontimeoutime)
                DBSession.add(newSessionObj)
                
                log=DBSession.query(Login_Session).filter_by(userid=usr.id).order_by(Login_Session.id.desc()).first()
                request.session['logged_session_id']=log.id
                headers = remember(request,usr.group)
                return HTTPFound(location=request.route_url('list'),headers=headers)
            else:
                request.session.flash('Please enter a valid User Name or Password!')
                return HTTPFound(location=request.route_url('login'))
        elif 'logged_session_id' in request.session and check_session(request.session['logged_session_id']): 
            session_login =DBSession.query(Login_Session).filter_by(id=request.session['logged_session_id'])
            headers = remember(request,session_login.group)
            request.session.flash('Welcome Back !')    
            return HTTPFound(location=request.route_url('list'),headers=headers)
        else:
            request.session.flash('Please enter a User Name or Password!')
            return HTTPFound(location=request.route_url('login'))
    return {}
コード例 #21
0
ファイル: auth.py プロジェクト: France-ioi/alkindi-backend
def login_with_participation_code(request):
    # This view handles the outcome of authentication performed by the
    # identity provider.
    now = datetime.utcnow()
    json_request = request.json_body
    code = json_request.get('code')
    if code is None:
        return {'error': 'missing code'}
    participation_id = find_participation_by_code(request.db, code)
    if participation_id is None:
        return {'error': 'no such participation'}
    participation = load_participation(request.db, participation_id)
    team_id = participation['team_id']
    user_id = get_team_creator(request.db, team_id)
    mark_participation_code_entered(request.db, participation_id, now)
    request.db.commit()
    # Clear the user's cached principals to force them to be refreshed.
    reset_user_principals(request)
    remember(request, str(user_id))
    # The view template posts the result (encoded as JSON) to the parent
    # window, causing the frontend to update its state.
    return {
        'success': True,
        'user_id': user_id,
        'csrf_token': request.session.get_csrf_token()
    }
コード例 #22
0
ファイル: auth.py プロジェクト: faddai/pyramidCrm
def login_view(request):
    """
        Login view
    """
    log.debug("# Login page")
    form = Form(authSchema,
                buttons=(Button(name="submit",
                                title="Valider",
                                type='submit'),))
    nextpage = request.params.get('nextpage') or request.route_url('index')
    app_struct = {'nextpage':nextpage}
    myform = form.render(app_struct)
    fail_message = None
    if 'submit' in request.params:
        log.debug(" + Validating authentication")
        controls = request.params.items()
        try:
            datas = form.validate(controls)
        except ValidationFailure, err:
            log.debug("Erreur d'authentification")
            myform = err.render()
            request.session.flash(_(request, u"Authentication error"), "error")
            return {'title':"Login page",
                    'form':myform,}
        log.debug("  + Validation ok, redirecting")
        log.debug("     -> {0}".format(nextpage))
        login = datas['login']
        # Storing the datas in the session
        remember(request, login)
        return HTTPFound(location=nextpage)
コード例 #23
0
ファイル: views.py プロジェクト: sakal/pyramid-watchshop
    def login_form_process(self):
        """Process login form.
        Render form if attempt_authorize was failed
        and redirect to root '/' of site.
        Return form in 'form' key.
        
        @todo redirect to request_from url
        @todo process csrf value"""
        schema = AuthSchema()
        form = Form(schema, buttons=('submit',))
        if 'submit' in self.request.POST:
            controls = self.request.POST.items()
            values = None
            try:
                appstruct = form.validate(controls)
            except ValidationFailure, e:
                return render_to_response(
                    'templates/auth_form.jinja2',
                    {'form': e.render()}
                )

            # make here call of attempt_login
            if self.user_helper.attempt_authorize(
                appstruct['login'],
                appstruct['password']):
                remember(self.request, appsctruct['login'])
                return HTTPFound("/")
            else:
                return render_to_response(
                    'templates/auth_form.jinja2',
                    {'form':form.render(appstruct=appstruct)}
                )

            return HTTPFound('/')
コード例 #24
0
ファイル: views.py プロジェクト: robert118/ztq
def login(request):
    login_url = request.route_url('login')
    referrer = request.url
    if referrer == login_url:
        referrer = '/' # never use the login form itself as came_from
    came_from = request.params.get('came_from', referrer)
    message = ''
    login = '******'
    password = ''
    from utils.password import get_password
    if 'form.submitted' in request.params:
        login = request.params['login']
        password = request.params['password']
        try:
            if get_password() == password:
                headers = remember(request, login)
                return HTTPFound(location = came_from, headers = headers)
        except:
            if USERS.get(login) == password:
                headers = remember(request, login)
                return HTTPFound(location = came_from, headers = headers)
        message = 'Failed login'


    return dict(
        message = message,
        url = request.application_url + '/login',
        came_from = came_from,
        login = login,
        password = password,
        )
コード例 #25
0
ファイル: confirm_acc.py プロジェクト: RaHus/portal
def linkedin_confirm_view(request):
    code = request.matchdict.get('code')
    user = DBSession.query(User).filter(User.ver_code == code).first()
    if not user:
        return HTTPFound('/logout?no_redirect=1')
    remember(request, user.id)
    flow = get_oauth_flow_linkedin(request)
    return HTTPFound(flow.step1_get_authorize_url())
コード例 #26
0
ファイル: views.py プロジェクト: nikitos/npui
def client_oauth_register(request, regdict):
	nxt = request.route_url('access.cl.home')
	loc = get_localizer(request)
	headers = None
	#if authenticated_userid(request):
	#	 return HTTPSeeOther(location=nxt)

	cfg = request.registry.settings
	rate_id = int(cfg.get('netprofile.client.registration.rate_id', 1))
	state_id = int(cfg.get('netprofile.client.registration.state_id', 1))

	errors = {}
	sess = DBSession()

	login = regdict.get('username', None)
	passwd = regdict.get('password', None)
	email = regdict.get('email', None)
	name_family = regdict.get('familyname', '')
	name_given = regdict.get('givenname', '')

	### !!!!! What if user changes his password in out database?!
	if login is not None and passwd is not None:
		q = sess.query(AccessEntity).filter(AccessEntity.nick == login, AccessEntity.access_state != AccessState.block_inactive.value)
		if q is not None:
			for user in q:
				if user.password == passwd:
					headers = remember(request, login)
					return headers

	if headers is None:
		ent = PhysicalEntity()
		ent.nick = login
		ent.email = email
		ent.name_family = name_family
		ent.name_given = name_given
		ent.state_id = state_id

		stash = Stash()
		stash.entity = ent
		stash.name = loc.translate(_('Primary Account'))

		acc = AccessEntity()
		acc.nick = login
		acc.password = passwd
		acc.stash = stash
		acc.rate_id = rate_id
		acc.state_id = state_id
		ent.children.append(acc)
		
		sess.add(ent)
		sess.add(stash)
		sess.add(acc)
		sess.flush()
		headers = remember(request, login)
		return headers

	else:
		return False
コード例 #27
0
ファイル: login.py プロジェクト: jladage/Kotti
def login(context, request):
    """
    Login view.  Renders either the login or password forgot form templates or
    handles their form submission and redirects to came_from on success.

    :result: Either a redirect response or a dictionary passed to the template
             for rendering
    :rtype: pyramid.httpexceptions.HTTPFound or dict
    """

    principals = get_principals()

    came_from = request.params.get(
        'came_from', request.resource_url(context))
    login, password = u'', u''

    if 'submit' in request.POST:
        login = request.params['login'].lower()
        password = request.params['password']
        user = _find_user(login)

        if (user is not None and user.active and
                principals.validate_password(password, user.password)):
            headers = remember(request, user.name)
            request.session.flash(
                _(u"Welcome, ${user}!",
                  mapping=dict(user=user.title or user.name)), 'success')
            user.last_login_date = datetime.now()
            return HTTPFound(location=came_from, headers=headers)
        request.session.flash(_(u"Login failed."), 'error')

    if 'reset-password' in request.POST:
        login = request.params['login']
        user = _find_user(login)
        if user is not None and user.active:
            email_set_password(
                user, request,
                template_name='kotti:templates/email-reset-password.pt')
            request.session.flash(_(
                u"You should be receiving an email with a link to reset your "
                u"password. Doing so will activate your account."), 'success')
        else:
            request.session.flash(
                _(u"That username or email is not known by this system."),
                'error')
        headers = remember(request, user.name)
        return HTTPFound(location=came_from, headers=headers)

    return {
        'url': request.application_url + '/@@login',
        'came_from': came_from,
        'login': login,
        'password': password,
        'register': asbool(get_settings()['kotti.register']),
        }
コード例 #28
0
ファイル: views.py プロジェクト: theun/in.nuribom.com
def login(request):
    login_url = request.route_path('login')
    referrer = request.url
    if referrer == login_url:
        referrer = request.route_path('blog_list') # never user the login from itself as came_from
    came_from = request.params.get('came_from', referrer)
    log.error("[%s] CAME FROM: %s", request.method, came_from)
    message = ''
    login = ''
    password = ''
    activate = ''

    if request.method == "GET":
        login = get_remember(request) 
        if login:
            log.info('remember me is success')
            headers = remember(request, login)
            return HTTPFound(location=came_from, headers=headers)    
                
        if 'login' in request.params:
            login = request.params['login']
            user = User.by_username(login)
            if user and user.activate == 'REQUESTED':
                activate = user.activate
    
        return dict(url= request.application_url + '/login',
                    came_from=came_from,
                    login=login,
                    password=password,
                    activate=activate,
                    )
    elif request.method == "POST":
        login = request.params['login']
        password = request.params['password']
        user = User.by_username(login)
        if user and user.activate == 'REQUESTED':
            user.set_password(password)
            user.groups.append('group:employee')
            user.save(safe=True)
            headers = remember(request, login)
            return HTTPFound(location=request.route_path('blog_list'), headers=headers)
        elif user and user.validate_password(password):
            headers = remember(request, login)
            request.response.headerlist.extend(headers)
    
            remember_me = request.params.get('PersistentCookie', 'no')
            if remember_me == 'yes' :
                set_remember(request, str(user.id))
                return HTTPFound(location=came_from, headers=request.response.headers)
            else:
                reset_remember(request)
                request.response.headerlist.extend(headers)
                return HTTPFound(location=came_from, 
                                 headers=request.response.headers)
        request.session.flash('Failed login')
コード例 #29
0
ファイル: viewsUser.py プロジェクト: dotlambda/muesli
def login(request):
	form = FormValidator(UserLogin())
	if request.method == 'POST' and form.validate(request.POST):
		user = request.db.query(models.User).filter_by(email=form['email'], password=sha1(form['password'].encode('utf-8')).hexdigest()).first()
		if user is not None:
			security.remember(request, user.id)
			request.user = user
			url = request.route_url('start')
			return HTTPFound(location=url)
		request.session.flash(u'Nicht gefunden', queue='errors')
	return { 'form': form, 'user': security.authenticated_userid(request) }
コード例 #30
0
ファイル: login.py プロジェクト: toway/mba
def login(context, request):

    user = get_user(request)
    if user :
        # already login, redirect to home page
        return HTTPFound(location="/")
    
    schema = LoginSchema(validator=user_password_match_validator).bind(request=request)

    form = deform.Form(schema,
                       buttons=[deform.form.Button(u'submit', title=u'登录', css_class="btn btn-primary")],
                       css_class="border-radius: 4px;box-shadow: 0 1px 3px rgba(0,0,0,0.075);" )
    rendered_form = None

    principals = get_principals()

    came_from = request.params.get(
        'came_from', request.resource_url(context))
    login, password = u'', u''

    if 'submit' in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except ValidationFailure, e:
            # msg = [ _(u"%s is %s")  for (k,v) in  e.error.items() ]    
            # msg = u",".join( [m for m in e.error.messages] )
            request.session.flash(_(u"登陆失败" ), 'danger')
            #request.session.flash(_(u"登陆失败:%s" % e.error), 'error')
            # showing 登陆失败 {'password': u'shorting than miminum length 6'}
            rendered_form = e.render()
        else:
            user = _find_user(appstruct['email_or_username'])
            if (user is not None and user.status == user.ACTIVE and
                    principals.validate_password(appstruct['password'], user.password)):
                headers = remember(request, user.name)

                # TODO: i18n does not work
                # request.session.flash(
                #     _(u"欢迎登陆, ${user}!",
                #       mapping={'user': '******' }), 'success')
                # request.session.flash(
                #     _(u"欢迎登陆, %s!" % (user.real_name or user.name ) ), 'success')
                user.last_login_date = datetime.now()
                if came_from == 'login':
                    came_from = '/'
                return HTTPFound(location=came_from, headers=headers)

            elif user.status == user.INACTIVE:
                return HTTPFound(location='/register_finish')
            elif user.status == user.TO_FULLFIL_DATA:
                headers = remember(request, user.name)
                return HTTPFound(location='/register_details', headers=headers)

            request.session.flash(_(u"登陆失败,用户名或密码错误."), 'danger')
コード例 #31
0
ファイル: test_testing.py プロジェクト: sarvex/pyramid
    def test_testing_securitypolicy_remember_result(self):
        from pyramid.security import remember

        config = self._makeOne(autocommit=True)
        pol = config.testing_securitypolicy(
            'user',
            ('group1', 'group2'),
            permissive=False,
            remember_result=True,
        )
        request = DummyRequest()
        request.registry = config.registry
        val = remember(request, 'fred')
        self.assertEqual(pol.remembered, 'fred')
        self.assertEqual(val, True)
コード例 #32
0
def login(request):
    user_id = request.POST.get('userId', '')
    #user_id =  user_id.upper()
    pwd = request.POST.get('password', '')
    user = DBSession.query(User).filter(
        func.upper(User.id) == func.upper(user_id)).one()

    if user is not None and user.check_password(pwd):
        claims = {
            "iss": user_id,
            "username": user.Login,
            "userlanguage": user.Language
        }
        jwt = make_jwt(request, claims)
        print(jwt)
        print(request)
        response = Response(body='login success', content_type='text/plain')
        remember(response, jwt)
        print(response)
        transaction.commit()
        return response
    else:
        transaction.commit()
        return HTTPUnauthorized()
コード例 #33
0
    def login_success(self, appstruct):
        user = get_user(self.request, appstruct['username'])
        if user is None:
            return self.bad_login()
        if not user.validate_password(appstruct['password']):
            return self.bad_login()

        # After we've validated the user's username and password, we
        # call 'pyramid.security.remember' to effectively set the
        # authentication cookie:
        headers = remember(self.request, user.__name__)
        self.request.session.flash(u"Welcome, {0}!".format(user.title),
                                   "success")
        return HTTPFound(location=self.request.application_url,
                         headers=headers)
コード例 #34
0
def register(request):
    if request.authenticated_userid:
        return HTTPFound(location=request.route_url('home'))
    form = CredentialsForm(request.POST)
    if request.method == 'POST' and form.validate():
        u = mymodel.Users(username=form.username.data)
        u.set_password(form.password.data.encode('utf8'))
        try:
            u.save()
        except mongoengine.errors.NotUniqueError as e:
            form.username.errors.append('Username already taken')
            return {'form': form, 'title': 'Sign Up'}
        return HTTPFound(location=request.route_url('home'),
                         headers=remember(request, u.username))
    return {'form': form, 'title': 'Sign Up'}
コード例 #35
0
    def login_handler(self):
        request = self.request
        username = request.params['username']
        password = request.params['password']
        user = Session.query(User).filter_by(username=username).first()
        if user and user.password == password:
            headers = remember(request, username)
            return HTTPFound(location=request.route_url('home'),
                             headers=headers)

        return dict(
            form_error='Invalid username or password',
            username=username,
            password=password,
        )
コード例 #36
0
ファイル: auth.py プロジェクト: nextgis/nextgisweb_groza
def login(request):
    result = {'login': False}
    try:
        user = User.filter_by(keyname=request.POST['login'].strip()).one()

        if user.password == request.POST['password']:
            headers = remember(request, user.id)
            if user.disabled:
                return result
            result['login'] = True
            return Response(headers=headers, json=result)
        else:
            return result
    except NoResultFound:
        return result
コード例 #37
0
def login(request):

    message = 'Please log in.'

    if 'form.login_submitted' in request.params:
        username = request.params['username']
        password = request.params['password']
        if get_password(username) == password:
            headers = remember(request, username)
            return HTTPFound(location=request.route_url('home'),
                             headers=headers)
        message = 'Login failed. Try again.'

    body = render('templates/login.pt', dict(), request)
    return dict(message=message, body=body)
コード例 #38
0
ファイル: __init__.py プロジェクト: miohtama/horus
def authenticated(request, userid):
    """Sets the auth cookies and redirects to the page defined
    in horus.login_redirect, which defaults to a view named 'index'.
    """
    settings = request.registry.settings
    headers = remember(request, userid)
    autologin = asbool(settings.get('horus.autologin', False))

    if not autologin:
        Str = request.registry.getUtility(IUIStrings)
        FlashMessage(request, Str.authenticated, kind='success')

    location = get_config_route(request, 'horus.login_redirect')

    return HTTPFound(location=location, headers=headers)
コード例 #39
0
ファイル: persona.py プロジェクト: lelou6666/clincoded
def login(request):
    """View to check the persona assertion and remember the user"""
    login = request.authenticated_userid
    if login is None:
        namespace = userid = None
    else:
        namespace, userid = login.split('.', 1)
    if namespace != 'persona':
        request.session['user_properties'] = {}
        request.response.headerlist.extend(forget(request))
        raise LoginDenied()
    request.session['user_properties'] = request.embed('/current-user',
                                                       as_user=userid)
    request.response.headerlist.extend(remember(request, 'mailto.' + userid))
    return request.session
コード例 #40
0
ファイル: lib.py プロジェクト: sherah/h
def set_user(request, user):
    # Must extract the id here since pyramid_tm will cause the database
    # session to be invalid by the time this runs.
    if user is not None:
        headers = remember(request, user.id)
    else:
        headers = forget(request)

    def _set_auth_headers(request, response):
        response.headerlist.extend(getattr(request, '_user_modified'))

    if not hasattr(request, '_user_modified'):
        request.add_response_callback(_set_auth_headers)

    setattr(request, '_user_modified', headers)
コード例 #41
0
ファイル: account.py プロジェクト: silky/floof
def safe_openid_login(request, identity_owner, identity_url):
    """Helper function, catches any exceptions that may be raised on OpenID
    login."""
    try:
        auth_headers = security.remember(
            request, identity_owner, openid_url=identity_url)
    except OpenIDAuthDisabledError:
        request.session.flash("Your OpenID is no longer accepted as your "
            "account has disabled OpenID authentication.",
            level='error', icon='key--exclamation')
    except OpenIDNotFoundError:
        request.session.flash("I don't recognize your OpenID identity.",
            level='error', icon='key--exclamation')
    else:
        return auth_headers
コード例 #42
0
def login_view(request):
    """Login view: GET request loads the page. POST request logs the user in, and error handles for bad login input."""
    if request.method == 'GET':
        return {}
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        try:
            if is_authorized(request, username, password):
                headers = remember(request, username)
                return HTTPFound(request.route_url('portfolio'),
                                 headers=headers)
            return {'error': 'Username/password combination invalid.'}
        except AttributeError:  # pragma: no cover
            return {"error": "Username/password combination invalid."}
コード例 #43
0
def remember_login(context, request, userid, max_age):
    remember_headers = remember(request, userid, max_age=max_age)

    # log the time on the user's profile, unless in read only mode
    read_only = not is_normal_mode(request.registry)
    if not read_only:
        profiles = find_profiles(context)
        if profiles is not None:
            profile = profiles.get(userid)
            if profile is not None:
                profile.last_login_time = datetime.utcnow()

    # and redirect
    came_from = request.session.pop('came_from')
    return HTTPFound(headers=remember_headers, location=came_from)
コード例 #44
0
def login(request):
    """Authenticate a user by username/password"""
    username = request.params.get('username', '')
    error = ''
    if request.method == 'POST':
        error = "Login Failed"
        authenticated = False
        try:
            authenticated = do_login(request)
        except ValueError as e:
            error = str(e)
        if authenticated:
            headers = remember(request, username)
            return HTTPFound(request.route_url('home'), headers=headers)
    return {'error': error, 'username': username}
コード例 #45
0
ファイル: views.py プロジェクト: tiagokrebs/zapizza-backend
    def login(self):
        request = self.request
        json_body = self.request.json_body

        if 'username' not in json_body:
            msg = 'Username não informado'
            res = dumps(dict(error=dict(code=409, message=msg)),
                        ensure_ascii=False)
            return HTTPConflict(body=res,
                                content_type='application/json; charset=UTF-8')
        username = json_body['username']

        if 'password' not in json_body:
            msg = 'Password não informado'
            res = dumps(dict(error=dict(code=409, message=msg)),
                        ensure_ascii=False)
            return HTTPConflict(body=res,
                                content_type='application/json; charset=UTF-8')
        password = json_body['password']

        user = User.by_username_email(username)
        if user and user.password == password:
            headers = remember(request, user.username)
            msg = 'Login efetuado com sucesso'
            token_data = {'aud': 'idToken', 'username': user.username}
            token = generate_token(request=self.request, data=token_data)
            if user.register_confirm:
                confirmed = True
            else:
                confirmed = False
            res = dumps(dict(data=dict(code=200,
                                       message=msg,
                                       userId=user.username,
                                       idToken=token.decode('utf-8'),
                                       expiresIn=3600,
                                       emailConfirmed=confirmed,
                                       firstName=user.first_name,
                                       lastName=user.last_name)),
                        ensure_ascii=False)
            return HTTPOk(headers=headers,
                          body=res,
                          content_type='application/json; charset=UTF-8')

        msg = 'Username ou senha inválidos'
        res = dumps(dict(error=dict(code=409, message=msg)),
                    ensure_ascii=False)
        return HTTPConflict(body=res,
                            content_type='application/json; charset=UTF-8')
コード例 #46
0
    def login(self):
        """
        Login view.  Renders either the login or
        password forgot form templates or
        handles their form submission and redirects to came_from on success.
        :result: Either a redirect response or a dictionary passed
                 to the template
                 for rendering
        :rtype: pyramid.httpexceptions.HTTPFound or dict
        """

        principals = get_principals()
        came_from = self.request.params.get(
            'came_from', self.request.resource_url(self.context))
        login, password = u'', u''
        try:
            login = self.request.params["username"].lower()
            password = self.request.params["password"]
        except Exception as e:
            print e
            try:
                params = json.loads(self.request.body)
            except Exception as e:
                print e
                params = dict(urlparse.parse_qsl(self.request.body))

            login = params.get("username", "")
            password = params.get("password", "")
        if login and password:
            user = kotti_login._find_user(login)
            if user is None:
                return {"status": "failed", "message": "No user was found"}
            if (principals.validate_password(password, user.password)):

                headers = remember(self.request, user.name)
                print headers
                user.last_login_date = datetime.now()
                return httpexc.HTTPFound(
                    location="/@@login-status?from_login=1", headers=headers)
            return {"status": "failed", "message": "Incorrect password"}

        return {
            'status': 'failed',
            'url': self.request.application_url + '/@@login',
            'came_from': came_from,
            'login': login,
            'message': 'No user data was sent'
        }
コード例 #47
0
ファイル: login.py プロジェクト: scottwis/substanced
def login(context, request):
    login_url = request.sdiapi.mgmt_path(request.context, 'login')
    referrer = request.url
    if '/auditstream-sse' in referrer:
        # If we're being invoked as the result of a failed request to the
        # auditstream sse view, bail.  Otherwise the came_from will be set to
        # the auditstream URL, and the user who this happens to will eventually
        # be redirected to it and they'll be left scratching their head when
        # they see e.g. "id: 0-10\ndata: " when they log in successfully.
        return HTTPForbidden()
    if login_url in referrer:
        # never use the login form itself as came_from
        referrer = request.sdiapi.mgmt_path(request.virtual_root)
    came_from = request.session.setdefault('sdi.came_from', referrer)
    login = ''
    password = ''
    if 'form.submitted' in request.params:
        try:
            check_csrf_token(request)
        except:
            request.session.flash('Failed login (CSRF)', 'error')
        else:
            login = request.params['login']
            password = request.params['password']
            adapter = request.registry.queryMultiAdapter(
                (context, request),
                IUserLocator
                )
            if adapter is None:
                adapter = DefaultUserLocator(context, request)
            user = adapter.get_user_by_login(login)
            if user is not None and user.check_password(password):
                request.session.pop('sdi.came_from', None)
                headers = remember(request, get_oid(user))
                request.registry.notify(LoggedIn(login, user, context, request))
                return HTTPFound(location = came_from, headers = headers)
            request.session.flash('Failed login', 'error')

    # Pass this through FBO views (e.g., forbidden) which use its macros.
    template = get_renderer('substanced:sdi/views/templates/login.pt'
                           ).implementation()
    return dict(
        url = request.sdiapi.mgmt_path(request.virtual_root, '@@login'),
        came_from = came_from,
        login = login,
        password = password,
        login_template = template,
        )
コード例 #48
0
    def authenticate_user(self,
                          user: IUser,
                          login_source: str,
                          location: str = None) -> Response:
        """Make the current session logged in session for this particular user.

        How to authenticate user using the login service (assuming you have done password match or related yourself):

        .. code-block:: python

            from websauna.system.user.utils import get_login_service

            def my_view(request):

                # load user model instance from database
                # user = ...

                login_service = get_login_service(request)
                response = login_service.authenticate_user(user, "my-login-source")

        :raise AuthenticationFailure: If login cannot proceed due to disabled user account, etc.

        :return: HTTPResponse what should happen as post-login action
        """
        request = self.request
        settings = request.registry.settings

        require_activation = asbool(
            settings.get('websauna.require_activation', True))
        allow_inactive_login = asbool(
            settings.get('websauna.allow_inactive_login', False))

        if (not allow_inactive_login) and require_activation and (
                not user.is_activated()):
            raise AuthenticationFailure(
                'Your account is not active, please check your e-mail. If your account activation email as expired please request a password reset.'
            )

        if not user.can_login():
            raise AuthenticationFailure(
                'This user account cannot log in at the moment.')

        user_registry = get_user_registry(request)
        token = user_registry.get_session_token(user)
        headers = remember(request, token)
        # assert headers, "Authentication backend did not give us any session headers"

        return self.do_post_login_actions(user, headers, location)
コード例 #49
0
def accountants_login(request):
    """
    This view lets accountants log in (using a login form).

    If a person is already logged in, she is forwarded to the dashboard.
    """
    logged_in = authenticated_userid(request)

    LOG.info("login by %s", logged_in)

    if logged_in is not None:
        return get_dashboard_redirect(request)

    form = deform.Form(
        AccountantLogin(),
        buttons=[
            deform.Button('submit', _(u'Submit')),
            deform.Button('reset', _(u'Reset'))
        ],
    )

    # if the form has been used and SUBMITTED, check contents
    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
        except ValidationFailure, e_validation_failure:
            request.session.flash(_(u"Please note: There were errors, "
                                    "please check the form below."),
                                  'message_above_form',
                                  allow_duplicate=False)
            return {'form': e_validation_failure.render()}

        # get user and check pw...
        login = appstruct['login']
        password = appstruct['password']

        try:
            checked = C3sStaff.check_password(login, password)
        except AttributeError:  # pragma: no cover
            checked = False
        if checked:
            LOG.info("password check for %s: good!", login)
            headers = remember(request, login)
            LOG.info("logging in %s", login)
            return HTTPFound(request.route_url('dashboard'), headers=headers)
        else:
            LOG.info("password check: failed for %s.", login)
コード例 #50
0
def login_view(request):
    main_view = route_url('main', request)
    came_from = request.params.get('came_from', main_view)

    post_data = request.POST
    if 'submit' in post_data:
        login = post_data['login']
        password = post_data['password']

        if User.check_password(login, password):
            headers = remember(request, login)
            request.session.flash(u'Logged in successfully.')
            return HTTPFound(location=came_from, headers=headers)

    request.session.flash(u'Failed to login.')
    return HTTPFound(location=came_from)
コード例 #51
0
ファイル: login.py プロジェクト: twu/pypicloud
def handle_register_request(request, username, password):
    """Process a request to register a new user"""
    if not request.access.allow_register() and not request.access.need_admin():
        return HTTPForbidden()
    username = username.strip()
    try:
        if len(username) > 100 or len(username) < 1:
            raise ValueError("Username must be between 1 and 100 characters")
        if len(password) > 100:
            raise ValueError("Password cannot exceed 100 characters")
        if register_new_user(request.access, username, password):
            request.response.headers.extend(remember(request, username))
    except ValueError as e:
        request.response.status_code = 400
        return {"code": 400, "message": e.args[0]}
    return request.response
コード例 #52
0
 def login (self):
     request = self.request
     access_handler = request.registry.SDSAccessHandler
     user_name = request.params.get ('login')
     user_pass = request.params.get ('password')
     err = access_handler.login (user_name, user_pass)
     ret = {}
     if err is not None:
         ret ['error'] = err
         return ret
     
     ret ['success'] = True
     headers = remember (request, user_name)
     request.response.headers.extend (headers)
     
     return ret
コード例 #53
0
def login_view(request):
    """Login page view."""
    login_form = LoginForm(request.POST)
    if request.method == 'POST' and login_form.validate():
        usrname = request.params.get('usrname')
        pswd = request.params.get('pswd')
        # usrname = login_form.usrname.data
        # pswd = login_form.pswd.data
        usrcheck = usrname == 'owner'
        pwdcheck = sha256_crypt.verify(pswd, os.environ.get('LJ_AUTH'))
        if usrcheck and pwdcheck:
            headers = remember(request, usrname)
            return HTTPFound(request.route_url('list'), headers=headers)
        return HTTPForbidden()
        # return HTTPFound(request.route_url('login'))
    return {'title': 'Login', 'form': login_form}
コード例 #54
0
ファイル: views.py プロジェクト: Fidelz/code
 def login(self):
     request = self.request
     form = Login(request.POST)
     if request.method == 'POST' and form.validate():
         username = form.username.data
         password = form.password.data
         query = DBSession.query(UserLogin).filter_by(username=username,
                                                      password=password)
         correct_login = query.count()
         if correct_login:
             headers = remember(request, username)
             url = request.route_url('admin')
             return HTTPFound(location=url, headers=headers)
     request.session.flash("Error: los datos no son correctos.")
     url = request.route_url('home')
     return HTTPFound(location=url)
コード例 #55
0
    def sign_in_out(self):
        username = self.request.POST.get('username')
        redirect_to = 'home'

        if username:
            user = UserService.by_name(username)
            if user and user.verify_password(self.request.POST.get('password')):
                headers = remember(self.request, user.name)
            else:
                headers = forget(self.request)
                redirect_to = 'login'
        else:
            headers = forget(self.request)
            redirect_to = 'login'

        return HTTPFound(location=self.request.route_url(redirect_to), headers=headers)
コード例 #56
0
ファイル: auth.py プロジェクト: omh/yoshimi
    def login(self, email, password):
        """Logs in a user

        :param string email: The user's email
        :param string password" The user's password
        :return tuple: Tuple of HTTP headers to keep user logged in. False if
                       user could not be logged in.
        """
        user = self.load(email)
        if not user:
            return False

        if custom_app_context.verify(password, user.password_hash):
            return remember(self.req, email)

        return False
コード例 #57
0
def mutate(request):
    'Mutate user token'
    params = request.params
    if params.get('token') != request.session.get_csrf_token():
        return dict(isOk=0, message='Invalid session token')
    userID = authenticated_userid(request)
    # Mutate user code 
    user = db.query(User).get(userID)
    user.code = make_random_string(CODE_LEN)
    # Refresh cookie
    if not hasattr(request, 'response_headerlist'):
        request.response_headerlist = []
    request.response_headerlist.extend(remember(request, user.id, tokens=format_tokens(user)))
    # Return
    region_invalidate(get_properties, None, userID)
    return dict(isOk=1, code=user.code)
コード例 #58
0
def my_view_home(request):
    #nxt = request.params.get('next') or request.route_url('home')
    did_fail = False
    if 'login' in request.POST:
        #LOGIN PROCESSING
        user = login(request.POST["email"], request.POST["password"])
        if user:
            headers = remember(request, user.id)
            #return HTTPFound(location=nxt, headers=headers)
        else:
            did_fail = True
    return {
        'login': "",
        #'next': nxt,
        'failed_attempt': did_fail,
    }
コード例 #59
0
 def save_success(self, appstruct):
     user = self.request.user
     headers = None
     # if email was modified, we need to re-set the user's session
     email = appstruct['account_info']['email'].lower()
     if user.email != email:
         user.email = email
         headers = remember(self.request, user.email)
     user.fullname = appstruct['account_info']['fullname']
     if appstruct['affiliate_settings']['clickbank_affiliate_id']:
         self.request.user.set_property(
             'clickbank_affiliate_id',
             appstruct['affiliate_settings']['clickbank_affiliate_id'],
         )
     self.request.session.flash(u'Your changes have been saved.')
     return HTTPFound(location=self.request.path_url, headers=headers)
コード例 #60
0
ファイル: gallery.py プロジェクト: bennihepp/pyGallerid
 def login(self):
     context, request = self.context, self.request
     username = request.params['username']
     password = request.params['password']
     root = find_root(context)
     user = retrieve_user(root, username)
     if user is not None and user.authenticate(password):
         headers = remember(request, username)
         request.session.flash('Logged in successfully')
     else:
         headers = None
         request.session.flash('Login failed')
     #resp = render_view_to_response(context)
     #return resp
     url = request.resource_url(context)
     return HTTPFound(location=url, headers=headers)