Beispiel #1
0
def signin():
    '''
  Verify and signin a user.
  '''
    user = None
    user_verified = False
    pass_verified = False
    next = request.args.get('next', None)
    if request.method == 'POST':
        try:
            user = User.query(User.username == request.form.get(
                'username', '')).get()  # NOQA
        except Exception as ex:
            pass
        user_verified = True if user else False
        if (user and user.password and User.password.verify(
                request.form.get('password'), user.password)):
            sec.token = {'usr': user.username, 'uid': user.uid}
            pass_verified = True
            return redirect(next or url_for('root'))
        else:
            user = User()
            user.fill(username=request.form.get('username'))
    return render_template('signin.html',
                           page=None,
                           user=user,
                           form_action=url_for('signin', next=next),
                           next=next,
                           user_verified=user_verified,
                           pass_verified=pass_verified)
 def post(self, *args, **kwargs):
   email = self.request.get("email")
   code = self.request.get("code")
   password = self.request.get("password")
   site = Site.all().get()
   if email and not code:
     if User.send_recovery_email(email, site.title):
       self.response.out.write("The email has been sent. Please check your email to reset your password.")
       return True
     else:
       self.response.out.write("The email was not sent. Please try again.")
       return False
   elif email and code and password:
     user = User.get_by_email(email)
     if user:
       if user.set_password(password, site.secret):
         login = User.login(email, password, site)
         self.session["user"] = login
         user.destroy_token()
         self.redirect('/')
         return True
       else:
         self.response.out.write("An Error Occurred Resetting Password, Please try again.")
         return False
     else:
       self.response.out.write("Cannot Reset Password For This User")
       return False
   return False
Beispiel #3
0
def register():
    try:
        data = request.json
        email, password = data["email"], data["password"]

        if User.query.filter_by(email=email).count() > 0:
            return response(status=constants.ERROR,
                            message=constants.EMAIL_ALREADY_EXISTS)

        if not validate_email(email):
            return response(status=constants.ERROR,
                            message=constants.INVALID_EMAIL)

        user = User()
        user.email = email
        user.password = sha256_crypt.encrypt(str(password))

        db.session.add(user)
        db.session.commit()

        return response(status=constants.SUCCESS,
                        message=constants.REGISTRATION_SUCCESS)
    except Exception:
        return response(status=constants.ERROR,
                        message=constants.SOMETHING_WENT_WRONG,
                        status_code=422)
def add_user():
    # person = User(username='******', password='******')
    # session.add(person)
    # 增加多条数据
    session.add_all([User(username='******', password='******'), \
                     User(username='******', password='******')])

    session.commit()
Beispiel #5
0
 def create_user(self, email, username, password):
     user = User(user_name=username,
                 user_password=password,
                 user_email=email)
     user.hash_password()
     self.io.add([user])
     session = Session(user_id=user.user_id)
     self.io.add([session])
     self.request_handler.set_secure_cookie('session_id',
                                            session.session_id,
                                            expires_days=30)
Beispiel #6
0
    def default_context(self):

        """
        Returns a dictionary containing default
        context for all render calls
        """

        context = {

            # add request and session objects to default context
            'request': self.request,
            'session': self.session,

            # helper funcs which can be used within templates
            'format_timedelta': format_timedelta,
            'is_admin': is_admin,
            'len': len,
            'uri_for': self.uri_for,

        }

        # check if user is logged in
        user = users.get_current_user()
        if user is not None:
            # get user from datastore
            user_key = 'user-' + user.user_id()
            user_entity = User.get_by_id(user_key)
            # add user to context
            context['user'] = user_entity
        else:
            context['user'] = None

        # return default context
        return context
Beispiel #7
0
def load_users():
    with open(path.join(DATA_DIRECTORY, 'auth.json')) as fh:
        data = json.load(fh)

        for user in data['users']:
            if db_session.query(User).filter_by(email=user['email']).one_or_none() is None:
                addresses = user.pop('addresses')

                new_user_obj = User(**user)

                new_address_objs = [Address(**address) for address in addresses]
                new_user_obj.addresses = new_address_objs

                db_session.add(new_user_obj)
                # print("added", new_user_obj, new_address_objs)
                db_session.commit()
Beispiel #8
0
def create_user(operator, first_name, last_name, email, username, password, **kwargs):
    """
    Create a new user in the database with the given values.
    """
    # TODO Auditable stuff
    existing_user = maybe_get_user_by_email(email)
    if existing_user:
        raise UserAlreadyExistsError("A user with that email address exists.")
    name = "%s %s" % (first_name, last_name)
    lower_name = name.lower()
    user = User(first_name=first_name, last_name=last_name, email=email, username=username,
                lowercase_display_name=lower_name)
    user.password = User.encode_password(password)
    user.save()
    activity_log.log_user_created(user, operator)
    return user
Beispiel #9
0
    def default_context(self):
        """
        Returns a dictionary containing default
        context for all render calls
        """

        context = {

            # add request and session objects to default context
            'request': self.request,
            'session': self.session,

            # helper funcs which can be used within templates
            'format_timedelta': format_timedelta,
            'is_admin': is_admin,
            'len': len,
            'uri_for': self.uri_for,
        }

        # check if user is logged in
        user = users.get_current_user()
        if user is not None:
            # get user from datastore
            user_key = 'user-' + user.user_id()
            user_entity = User.get_by_id(user_key)
            # add user to context
            context['user'] = user_entity
        else:
            context['user'] = None

        # return default context
        return context
Beispiel #10
0
 def get(self):
   """Return the registration form."""
   return_url = self.request.get("return_url")
   template_values = {
     "user_form" : User.to_form(return_url, mode="add")
   }
   self.render_out("templates/register.html", template_values)
Beispiel #11
0
    def generate_otp(self):
        # Block users marked as blocked
        try:
            self.user = User.get_or_create(
                {'phone': self.phone, 'login_type': str(self.login_type)})
        except MultipleResultsFound as error:
            APIException(500, str(error))

        if self.user and self.user.blocked:
            self.message = USER_BLOCKED_TEXT
            return False

        self.otp_obj = AuthOtp.get_or_create({'user_id': self.user.id,
                                              'is_active': True},
                                             self.sign_up_ip)

        if not self.is_valid_otp_request():
            return False

        self.otp = get_random_otp()
        self.otp_obj.update_otp_obj(otp=self.otp,
                                    otp_counter=self.otp_obj.otp_counter + 1,
                                    retry_counter=0,
                                    expiry=(datetime.datetime.now() +
                                            datetime.timedelta(
                                                seconds=OTP_EXPIRY_TIME))
                                    )
        return True
Beispiel #12
0
    def dispatch(self):

        """
        Override dispatch() to provide simple auth support
        """

        # make sure user is logged in
        user = users.get_current_user()
        if user is None:
            # redirect user to login page if not logged in
            redirect_url = users.create_login_url(self.request.path_qs)
            return self.redirect(redirect_url)

        # get user entity from datastore
        user_entity_id = 'user-' + user.user_id()
        user_entity = User.get_by_id(user_entity_id)

        # ensure user entity exists and has complete profile
        if user_entity is None or not user_entity.has_profile:
            redirect_url = self.uri_for('update-profile')
            return self.redirect(redirect_url)

        # we have valid auth so lets make the user_entity available class-wide
        self.user_entity = user_entity

        # Dispatch the request.
        TemplateHandler.dispatch(self)
 def generate_admin_html(self, page, user):
     contents = Content.all().fetch(1000)
     roles = Role.all().fetch(1000)
     emaildata = {"contents": contents, "roles": roles}
     emailcontext = template.Context(emaildata)
     email_template = template.Template(open("templates/email.html").read())
     email_html = email_template.render(emailcontext)
     admindata = {
         "page_edit": Page.to_form(self.request.path, "edit", page.key()),
         "theme_edit": Theme.to_form(self.request.path, "edit", page.theme.key(), page.key()),
         "page_key": page.key(),
         "path": self.request.path,
         "permission_table": Permission.get_table(page.key()),
         "sections": (
             {
                 "name": section.name.replace("section_", "").capitalize(),
                 "theme_key": section.theme.key(),
                 "theme_html": section.theme.html,
                 "theme_css": section.theme.css,
                 "theme_js": section.theme.js,
                 "content": (
                     {
                         "title": content.title,
                         "content_edit": Content.to_edit_list("title", self.request.path),
                         "content_form": Content.to_form(
                             self.request.path, "edit", content.key(), section.key()
                         ),
                         "content_deepform": Content.to_form(self.request.path, rel_key=section.key()),
                     }
                     for content in section.get_contents()
                 ),
             }
             for section in page.get_sections()
         ),
         "page_form": Page.to_form(self.request.path, rel_key=self.ws.site.key()),
         "user_form": User.to_form(self.request.path),
         "user_list": User.to_edit_list("email", self.request.path, True),
         "user_edit_form": User.to_form(self.request.path, "edit", user.key()),
         "user_import": open("defaults/admin/user_import.html").read(),
         "images": self.ws.site.images_for_use(),
         "email_blast": email_html,
     }
     context = template.Context(admindata)
     admin_template = template.Template(open("defaults/admin/tabs.html").read())
     admin_html = admin_template.render(context)
     return admin_html
Beispiel #14
0
def authenticate(username, password):
    """
    验证密码
    :param username:
    :param password:
    :return:
    """
    return User.get_password(username) == hashed(password)  # 返回bool值
Beispiel #15
0
def signup():
    '''
  Register a new user.
  '''
    user = None
    pass_verified = None
    next = request.args.get('next', None)
    if request.method == 'POST':
        try:
            user = User()
            user.fill(**request.form.to_dict())
            pass_verified = request.form.get('verify') == request.form.get(
                'password')  # NOQA
            if user.valid() and user.unique and pass_verified:
                user.put()
                sec.token = {'usr': user.username, 'uid': user.uid}
                return redirect(next or url_for('root'))
        except Exception as ex:
            print('bad user')
            print(ex)
            return abort(500)
    return render_template('signup.html',
                           page=None,
                           user=user,
                           form_action=url_for('signup', next=next),
                           next=next,
                           pass_verified=pass_verified)
Beispiel #16
0
 def register(self, username, password):
     """
     用户注册数据交互操作
     :param username:
     :param password:
     :return:
     """
     self.db_session.add(User(name=username, password=hashed(password)))
     self.db_session.commit()
Beispiel #17
0
 def get(self):
   return_url = self.request.get("return_url")
   model_key = self.session['user']
   template_values = {
     'return_url': return_url, 
     'account_edit' : User.to_form(return_url, mode ="edit", model_key = model_key),
     'logout' : self.ws.users.create_logout_url(return_url)
   }
   self.render_out("templates/account.html", template_values)
Beispiel #18
0
def login():
  user = None
  pass_verified = False
  if request.method == 'POST':
    user = User.query(User.username == request.form.get('username')).get()
    if not user:
      user = User()
      user.fill(username=request.form.get('username'))
    if (user and user.password and
      User.password.verify(request.form.get('password'), user.password)):
      sec.token = {'username': user.username}
      pass_verified = True
      return redirect(url_for('auth.welcome'))
  try:
    return render_template('login.html',
                            auth=user, pass_verified=pass_verified)
  except TemplateNotFound:
    abort(404)
Beispiel #19
0
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        user = User(form.name.data, form.location.data, form.aboutMe.data)
        flash('Your profile has been updated.')
        return redirect(url_for('.user', userName=user.name))
    form.name.data = 'Castilho'
    form.location.data = 'jf'
    form.aboutMe.data = 'developer'
    return render_template('auth/edit_profile.html', form=form)
Beispiel #20
0
 def post(self):
   if 'register-email' not in self.request.arguments() or 'register-password' not in self.request.arguments() or 'confirm-password' not in self.request.arguments():
     self.json_out({'success': False,'message': 'Required parameter missing.'})
   if self.request.get('register-email') == "" or  self.request.get('register-password') == "" or  self.request.get('confirm-password') == "" or  self.request.get('confirm-password') != self.request.get('register-password'):
     self.json_out({'success': False,'message': 'Please enter a valid email address and password to register'})
   user = self.ws.users.get_current_user(self)
   wsuser = User.register_user(self.request.get('register-email'), self.request.get('register-password'), self.ws.site.secret, user)
   email_notifier.EmailNotifier.notify(Role.get_administrators(), '*****@*****.**', self.create_admin_content())
   email_notifier.EmailNotifier.notify([wsuser], '*****@*****.**', self.create_user_content())
   self.redirect(self.request.get("return_url") or "/")
 def is_current_user_admin(cls, handler):
   if u'user' in handler.session:
     user = User.get(handler.session['user'])
     role = Role.all().filter("name", "Administrator").get()
     if user.key() in role.users:
       return True
     else:
       return False
   else:
     return False
Beispiel #22
0
def authenticate(username, password):
    ret = {}
    if username and password:
        result = User.is_exists(username, hash(password))
        if result:
            ret['msg'] = 'ok'
        else:
            ret['msg'] = 'username or password error'
    else:
        ret['msg'] = 'username or password is empty'
    return ret
 def get(self):
   contents = Content.all().fetch(1000)
   theme_packages = ThemePackage.all().fetch(1000)
   themes = Theme.all().fetch(1000)
   pages = Page.all().fetch(1000)
   images = Image.all().fetch(1000)
   roles = Role.all().fetch(1000)
   sections = Section.all().fetch(1000)
   _users = User.all().fetch(1000)
   actions = ACTIONS
   template_values = {'logout_url':self.ws.users.create_logout_url('/'),'theme_packages': theme_packages,'themes': themes, 'images': images, 'pages': pages, 'contents':contents, 'roles':roles, 'users':_users, 'actions': actions, 'sections': sections, 'site': self.ws.site}
   self.response.out.write(template.render('templates/manage.html',template_values))
Beispiel #24
0
	def post(self, request):
		client_id = request.form["client_id"]
		temp_token = request.form["temp_token"]
		if request.session[client_id] != temp_token:
			return Forbidden("Wrong client_id and temp_token")
		user = User.get(username="******")
		consumer = Consumer.get(client_id=client_id)
		consumer.code = str(uuid4())
		consumer.save()
		ConsumerUser.get_or_create(consumer=consumer, user=user)
		params = {"code": consumer.code}
		return RedirectResponse("%s?%s" % (consumer.redirect_uri, urlencode(params)))
Beispiel #25
0
    def test_password_salts_are_random(self):
        u = User()
        u.password = '******'
        u2 = User()
        u2.password = '******'

        self.assertTrue(u.password_hash != u2.password_hash)
Beispiel #26
0
def create_user(operator,
                first_name,
                last_name,
                email,
                username,
                password,
                is_admin=False,
                **kwargs):
    """
    Create a new user in the database with the given values.
    """
    # TODO Auditable stuff
    existing_user = maybe_get_user_by_email(email)
    if existing_user:
        raise UserAlreadyExistsError("A user with that email address exists.")
    name = "%s %s" % (first_name, last_name)
    lower_name = name.lower()
    user = User(first_name=first_name,
                last_name=last_name,
                email=email,
                username=username,
                lowercase_display_name=lower_name,
                is_admin=is_admin)
    user.password = User.encode_password(password)
    user.save()
    activity_log.log_user_created(user, operator)
    return user
Beispiel #27
0
def register():
    form = RegistrationForm(request.form)

    if request.method == 'POST' and form.validate():
        if not (User.get_user_by_email_or_none(form.email.data)
                or User.get_user_by_username_or_none(form.username.data)):
            user = User()
            form.populate_obj(user)

            # store the email in lowercase form
            user.email = form.email.data.strip().lower()
            g.db.add(user)
            g.db.commit()

            session['current_user_id'] = user.id
            session['logged_in'] = True
            flash("Thanks for registering", 'success')
            return redirect(url_for('main.index'))

        flash('That email or username already exists!', 'error')

    return render_template('auth/registration.html', form=form)
Beispiel #28
0
def register():
    form = RegistrationForm(request.form)

    if request.method == 'POST' and form.validate():
        if not (User.get_user_by_email_or_none(form.email.data) or
                    User.get_user_by_username_or_none(form.username.data)):
            user = User()
            form.populate_obj(user)

            # store the email in lowercase form
            user.email = form.email.data.strip().lower()
            g.db.add(user)
            g.db.commit()

            session['current_user_id'] = user.id
            session['logged_in'] = True
            flash("Thanks for registering", 'success')
            return redirect(url_for('main.index'))

        flash('That email or username already exists!', 'error')

    return render_template('auth/registration.html', form=form)
	def read(self, file):
		result = {
			"errors" : [],
			"data" : [],
			"dialect" : None
		}
		csvio = StringIO.StringIO(file)
		dialect = csv.Sniffer().sniff(file)
		csvreader = csv.DictReader(csvio, dialect = dialect)
		for row in csvreader:
			result["data"].append(row)
			"""
			Here we need to render each user account
			store it and get ready to start sending emails etc.
			"""
			if not row.get('             E-MAIL  ADDRESS', None):
				result['errors'].append({
					"message" : "Could not retrieve field             E-MAIL  ADDRESS",
					"row" : row
				})
				continue
			new_user = User.get_by_email(row.get('             E-MAIL  ADDRESS', 'CANCEL'))
			if not new_user:
				site = Site.all().get()
				new_user = User.create_user(row.get('             E-MAIL  ADDRESS', 'NONE'), 'NONE', site.secret)
			new_user.firstname = row.get('FIRST NAME', None)
			new_user.lastname = row.get('LAST NAME', None)
			new_user.spouse = row.get('SPOUSE', None)
			new_user.address = row.get('ADDRESS LINE 1', None) + '\n' + row.get('ADDRESS LINE 2', None) + '\n' + row.get('CITY', None) + '\n' + row.get('STATE', None) + ',' + row.get('ZIP', None) + '\n' + row.get('COUNTRY', None)
			if row.get('PHONE NUMBER', None):
				new_user.phone = row.get('PHONE NUMBER', None)
			if row.get('FAX NUMBER', None):
				new_user.fax = row.get('FAX NUMBER', None)
			
			new_user.put()
		
		#clear the user cache
		cache.Cache().clear()
		return result
Beispiel #30
0
 def post(self):
   if 'user.email' not in self.request.arguments() or 'user.password' not in self.request.arguments():
     self.json_out({'success': False,'message': 'Login invalid, not a legitamate form'})
   if self.request.get('user.email') == "" or  self.request.get('user.password') == "":
     self.json_out({'success': False,'message': 'Please enter your email address and password to login'})
   login = User.login(self.request.get('user.email'),self.request.get('user.password'),self.ws.site)
   if login:
     self.session["user"] = login
     #print self.session["user"]
     self.redirect(self.request.get("return_url"))
   else:
     self.session.delete_item("user")
     self.redirect(self.request.get("return_url"))
Beispiel #31
0
    def get(self, *args, **kwargs):

        # get url to redirect to after updating
        next_url = self.request.get('next_url', default_value='/')
        # check if next_url is relative or absolute
        if bool(urlparse.urlparse(next_url).scheme):
            # abort if absolute url is given
            return self.abort(400, detail="Only relative URLs allowed")

        # make sure user is logged in
        user = users.get_current_user()
        if user is None:
            # redirect user to login page if not logged in
            login_url = users.create_login_url(self.request.path_qs)
            return self.redirect(login_url)

        # get or create user entity in datastore
        user_key = 'user-' + user.user_id()
        user_entity = User.get_or_insert(user_key)

        # check if the user entity has credentials
        if not user_entity.has_credentials():
            # create flow to begin oauth dance
            flow = user_entity.get_flow()
            flow.params['state'] = self.request.path_qs
            # get oauth2 redirect url
            auth_url = flow.step1_get_authorize_url()
            # redirect to El Goog
            return self.redirect(auth_url)

        # check if the user has a fully populated profile
        if not user_entity.has_profile:
            try:
                profile = self.call_api(user_entity.access_token)
            except UnauthorisedError:
                # refresh the auth token if not authorised
                user_entity.refresh_auth()
                profile = self.call_api(user_entity.access_token)
            # save profile to user model
            self.update_profile(user_entity, profile, user.email())

        # check if the user has a fully populated profile after updating, if
        # not we'll dump the user out to a page telling them we couldn't
        # authorise or retrieve their profile
        if not user_entity.has_profile:
            redirect_url = self.uri_for('profile-update-error')
            return self.redirect(redirect_url)

        # return to the url we came here from initially
        return self.redirect(next_url)
Beispiel #32
0
    def get(self, *args, **kwargs):

        # get url to redirect to after updating
        next_url = self.request.get('next_url', default_value='/')
        # check if next_url is relative or absolute
        if bool(urlparse.urlparse(next_url).scheme):
            # abort if absolute url is given
            return self.abort(400, detail="Only relative URLs allowed")

        # make sure user is logged in
        user = users.get_current_user()
        if user is None:
            # redirect user to login page if not logged in
            login_url = users.create_login_url(self.request.path_qs)
            return self.redirect(login_url)

        # get or create user entity in datastore
        user_key = 'user-' + user.user_id()
        user_entity = User.get_or_insert(user_key)

        # check if the user entity has credentials
        if not user_entity.has_credentials():
            # create flow to begin oauth dance
            flow = user_entity.get_flow()
            flow.params['state'] = self.request.path_qs
            # get oauth2 redirect url
            auth_url = flow.step1_get_authorize_url()
            # redirect to El Goog
            return self.redirect(auth_url)

        # check if the user has a fully populated profile
        if not user_entity.has_profile:
            try:
                profile = self.call_api(user_entity.access_token)
            except UnauthorisedError:
                # refresh the auth token if not authorised
                user_entity.refresh_auth()
                profile = self.call_api(user_entity.access_token)
            # save profile to user model
            self.update_profile(user_entity, profile, user.email())

        # check if the user has a fully populated profile after updating, if
        # not we'll dump the user out to a page telling them we couldn't
        # authorise or retrieve their profile
        if not user_entity.has_profile:
            redirect_url = self.uri_for('profile-update-error')
            return self.redirect(redirect_url)

        # return to the url we came here from initially
        return self.redirect(next_url)
Beispiel #33
0
    def post(self):
        # 获取前端参数
        username = self.get_argument("username", "").strip()
        password = self.get_argument("password", "").strip()
        repeat_password = self.get_argument("repeat_password", "").strip()
        # 一 校验参数
        # 判断非空
        if not all([username, password, repeat_password]):
            return self.write("参数错误")
        # 判断格式
        if not (len(username) >= 6 and len(password) >= 6
                and password == repeat_password):
            return self.write("格式错误")

        if User.check_username(username):
            return self.write("用户名已存在")
        # 加密 保留在实现
        passwd = pas_encryption(password)
        # 入库
        User.add_user(username, passwd)  # 存入user数据库
        # 返回数据

        return self.redirect("/login")
Beispiel #34
0
	def by_password(self, client_id, client_secret, username, password):
		try:
			user = User.get(username=username, password=password)
			print client_id, client_secret
			consumer = Consumer.get(client_id=client_id, client_secret=client_secret)
			ConsumerUser.get_or_create(consumer=consumer, user=user)
			consumer.access_token = str(uuid4())
			print consumer.access_token
			consumer.save()
			params = {"access_token": consumer.access_token}
			return JsonResponse(params)
		except DoesNotExist:
			params = {"error": "Wrong parameters"}
			return JsonResponse(params)
Beispiel #35
0
    def post(self):
        #获取前端的参数,strip()去掉空格
        username = self.get_argument("username", "").strip()
        password = self.get_argument("password", "").strip()
        repeat_password = self.get_argument("repeat_password", "").strip()

        # 校验参数
        # 判断参数是否为空
        if not all([username, password, repeat_password]):
            return self.write("参数错误")
        # 判断格式
        if not (len(username) >= 6 and len(password) >= 6
                and password == repeat_password):
            return self.write("格式错误")
        # 判断用户唯一
        if User.check_username(username):
            return self.write("用户名已存在")

        # 加密,pip install bcrypt
        passwd = pas_encryption(password)
        # 入库
        User.add_user(username, passwd)  #存入user数据
        # 返回数据
        return self.redirect("/login")
Beispiel #36
0
 def add_user(self, username, password, email, age, gender,):
     """
     进行用户注册
     :param username:
     :param password:
     :param email:
     :return:
     """
     if username and password:
         user = User(username=username, password=password, emial=email, age=age, gender=gender, )
         self.session.add(user)
         self.session.commit()
         return 'ok'
     else:
         return 'false'
Beispiel #37
0
def authentic(username, password):
    if username and password:
        result = User.is_exists(username, hash(password))
        if result:
            msg = 'ok'
        else:
            msg = 'username / password not match'
    else:
        result = False
        msg = 'empty username or password'
    ret = {
        'msg': msg,
        'result': result,
    }
    return ret
Beispiel #38
0
 def post(self):
     # 获取用户名和秘密
     username = self.get_argument("username", "").strip()
     password = self.get_argument("password", "").strip()
     if username and password:
         # 数据对比
         user = User.check_username(username)
         pas = user.password if user else ""
         if pas_encryption(password, pas, False) == pas.encode("utf8"):
             self.session.set("user", username)
             next = self.get_argument("next", "/")
             return self.redirect(next)  # 路由跳转
         else:
             return self.write("用户名或密码错误")
     else:
         return self.write("参数错误")
def signin_view(self, request):
    next = request.params.get('next') or request.route_url('home')
    context = {}
    if request.method == "POST":
        first_name = request.POST.get('first_name', '')
        last_name = request.POST.get('last_name', '')
        email_id = request.POST.get('email_id', '')
        password = request.POST.get('password', '')
        user_category = request.POST.get('user_category', '')
        new_user = User(first_name, last_name, email_id, user_category, password)
        if UserQuery().is_email_id_already_registered(email_id):
            context.update(email_id_already_registered=True)
        else:
            UserQuery().add_user(new_user)


    context.update({'next': next, })
    print "Adding Users to Database." + str(context.get('next'))
    return context
Beispiel #40
0
	def application_after_load(self, application):
		Consumer.drop_table(fail_silently=True)
		Consumer.create_table()
		User.drop_table(fail_silently=True)
		User.create_table()
		ConsumerUser.drop_table(fail_silently=True)
		ConsumerUser.create_table()
		user1 = User.create(username="******", password=self.hash_password("s"))
		user2 = User.create(username="******", password=self.hash_password("b"))
		consumer1 = Consumer.create(name="app1", client_id="1", client_secret=str(uuid4()), access_token="a1")
		consumer2 = Consumer.create(name="app2", client_id="2", client_secret="secret2", redirect_uri="http://localhost:8080/auth_usage/end")
		consumer3 = Consumer.create(name="app3", client_id="3", client_secret="secret3")
		ConsumerUser.create(consumer=consumer1, user=user1)
		print "app loaded"
    def post(cls):
        try:
            data = USER_SIGNUP_SCHEMA.load(request.get_json())
            user = User(**data)
            user.hash_password()
            user.save()
            sendOtp(user.username, user.phone_number, user.id)

            return {'Message': 'User Created'}, 200
        except ValidationError as e:
            print(e)
            return check_error(str(e))
        except NotUniqueError:
            return {'Message': 'User already exist'}, 500
Beispiel #42
0
def register(username, password, password_repeat):
    ret = {'msg': 'other error'}
    if username and password and password_repeat:
        if password == password_repeat:
            s = Session()
            user = s.query(User).filter_by(name=username).all()
            if user:
                msg = 'username is already exists'
            else:
                new_user = User(name=username, password=hash(password))
                s.add(new_user)
                s.commit()
                s.close()
                msg = 'ok'
        else:
            msg = 'password is different'
    else:
        msg = 'username or password is empty'
    ret['msg'] = msg
    return ret
Beispiel #43
0
    def get(self):

        # make sure user is logged in
        user = users.get_current_user()
        if user is None:
            self.abort(401)

        # make sure this is a valid oauth2 callback
        code = self.request.get('code', default_value=None)
        if code is None:
            return self.abort(400, detail='Not a valid OAuth2 callback')

        # pull user entity from datastore and set credentials
        user_key = 'user-' + user.user_id()
        user_entity = User.get_by_id(user_key)
        user_entity.set_credentials(code)

        # redirect to specified URL
        redirect_url = self.request.get('state')
        return self.redirect(redirect_url)
Beispiel #44
0
def register(username, password1, password2):
    ret = {'msg': 'other error', 'user_id': None}
    if username and password1 and password2:
        if password1 == password2:
            session = Session()
            user = session.query(User).filter_by(username=username).all()
            if user:
                msg = 'username is exists'
            else:
                new_user = User(username=username, password=hash(password1))
                session.add(new_user)
                session.commit()
                ret['user_id'] = new_user.id
                session.close()
                msg = 'ok'
        else:
            msg = 'password1 != password2'
    else:
        msg = 'username or password is empty'
    ret['msg'] = msg
    return ret
Beispiel #45
0
def signup():
  user = None
  pass_verified = None
  if request.method == 'POST':
    try:
      user = User()
      user.fill(**request.form.to_dict())
      pass_verified = request.form.get('verify') == request.form.get('password')
      if user.valid() and user.unique and pass_verified:
        user.put()
        sec.token = {'username': user.username}
        return redirect(url_for('auth.welcome'))
    except Exception as ex:
      print('bad user')
      print(ex)
  try:
    return render_template('signup.html', auth=user, pass_verified=pass_verified)
  except TemplateNotFound:
    abort(404)
Beispiel #46
0
    def _write(self):
        self.user = User.get_user_properties({
            'phone': self.phone,
            'login_type': str(self.login_type)
        })

        if not self.is_valid_otp():
            return False
        access_token = generate_access_token()
        self.token_obj = AccessToken.create_token_obj({
            'user_id': self.user.id,
            'token': access_token,
        })

        if self.login_type == 1:
            self.profile_obj = Student.get_or_create({"user_id": self.user.id})
        else:
            self.profile_obj = Tutor.get_or_create({"user_id": self.user.id})

        self.otp_obj.update_otp_obj(is_active=False)
        return True
Beispiel #47
0
    def post(self):
        # 获取用户名与密码
        username = self.get_argument("username", "").strip()
        password = self.get_argument("password", "").strip()
        # 验证 一般不需要

        #  将输入的明文密码与密文密码进行加密,是否等于密文密码。
        if username and password:
            # 数据对比
            user = User.check_username(username)  # 获取用户的实例
            pas = user.password if user else ""
            # 用传入的密码加存储的密码作为盐解密 然后对比数据库的加密密码
            if pas_encryption(password, pas, False) == pas.encode("utf8"):
                self.session.set("user", username)
                next = self.get_argument("next", "/")
                return self.redirect(next)  # 路由跳转
            else:
                return self.write("用户名和密码错误")

        # 设置会话
        else:
            return self.write("参数错误")
Beispiel #48
0
	def application_after_load(self, application):
		User.drop_table(fail_silently=True)
		User.create_table()
		UserAccount.drop_table(fail_silently=True)
		UserAccount.create_table()
		print "app loaded"
Beispiel #49
0
 def get_all_users():
     # choices for select field
     all_users = User.query().order(User.family_name)
     all_users_list = yield all_users.map_async(lambda x: (x.key.urlsafe(), str(x.given_name) + ' ' + str(x.family_name)))
     raise ndb.Return(all_users_list)
        def get(self):
            if self.ws.site is None:
                self.redirect("/install")
                return False
            path = self.request.path
            # print path
            user_control = ""
            user_label = ""

            def kv_q(x):
                x = x.split("=")
                if len(x) < 2:
                    return x[0]
                return {x[0]: x[1]}

            page = Page.get_by_name(path)
            if not page:
                self.error(404)
                return False
            if not self.permission_check(page):
                self.error(403)
                self.redirect("/")
                return False
            admin_html = ""
            if page:
                if not page.theme:
                    page.theme = Theme.create(
                        {
                            "name": ["default" + page.name],
                            "html": [open("defaults/template.html").read()],
                            "css": [open("defaults/template.css").read()],
                            "js": [""],
                        }
                    )
                    page.put()
                if not page.sections:
                    page.get_or_make_sections()
                user = self.ws.users.get_current_user(self)
                if user:
                    auth = [{"user_control": self.ws.users.create_account_url(path), "user_label": "Account"}]

                    if self.ws.users.is_current_user_admin(self):
                        admin_html = self.generate_admin_html(page, user)
                else:
                    auth = [
                        {"user_control": self.ws.users.create_register_url(path), "user_label": "Register"},
                        {"user_control": self.ws.users.create_login_url(path), "user_label": "Login"},
                    ]
                page_theme = page.theme
                page_content_template = template.Template(page.build_template())
                sections = page.get_sections()
                section_dict = {}
                site_users = User.all().fetch(1000)
                for section in sections:
                    section_dict[section.name] = section
                user_control_link = ""
                for control in auth:
                    user_control_link += "<a href='%s' class='account control'>%s</a>" % (
                        control["user_control"],
                        control["user_label"],
                    )
                page_content_template_values = {
                    "site_users": site_users,
                    "ws": self.ws,
                    "page": page,
                    "sections": section_dict,
                    "user_control_link": user_control_link,
                }
                page_content = self.render_string(page_content_template, page_content_template_values)
                page_template_html = open("defaults/outer.html").read()
                page_template = template.Template(page_template_html)
                template_values = {
                    "title": page.title,
                    "css": page_theme.css,
                    "content": page_content,
                    "js": page_theme.js,
                    "admin_content": admin_html,
                }
                self.render_string_out(page_template, template_values)
            else:
                self.error(404)
 def get_current_user(cls, handler):
   if 'user' in handler.session:
     user = User.get(handler.session['user'])
     return user
   else:
     return None