Exemplo n.º 1
0
 def post(self):
     username = self.request.get('username')
     password = self.request.get('password')
     verify = self.request.get('verify')
     email = self.request.get('email')
     if not utils.valid_username(username) or not utils.valid_password(
             password) or (not utils.valid_email(email)
                           and "" != email) or password != verify:
         errorUsername = ""
         errorPassword = ""
         errorVerify = ""
         errorEmail = ""
         if not utils.valid_username(username):
             errorUsername = "******"
         if not utils.valid_password(password):
             errorPassword = "******"
         if not utils.valid_email(email) and "" != email:
             errorEmail = "That's not a valid email."
         if password != verify:
             errorVerify = "Your passwords didn't match."
         self.render('signup.html',
                     errorUsername=errorUsername,
                     errorPassword=errorPassword,
                     errorVerify=errorVerify,
                     errorEmail=errorEmail,
                     username=username,
                     email=email)
     else:
         if not model.User.by_name(username):
             user = model.User.save_user(username, password)
             self.set_secure_cookie('user_id', str(user.key().id()))
             self.redirect('/')
         else:
             errorUsername = '******'
             self.render('signup.html', errorUsername=errorUsername)
Exemplo n.º 2
0
 def post(self):
   user_email = self.request.get('email','')
   user_password = self.request.get('password')
   user_cpassword = self.request.get('confirmpassword')
   q = database.Query(database.User)
   q.filter("email =", user_email)
   total = q.count()
   if ((user_email and utils.valid_email(user_email)) and (user_password == user_cpassword) and total == 0):
     user_uuid = str(uuid.uuid1())
     user_obj = database.User(key_name = user_email, email = user_email, password = base64.b64encode(user_password), is_verify = False)
     user_obj.put()
     database.Verify(user=user_obj, uuid=user_uuid).put()
     sender = '*****@*****.**'
     to = user_email
     mail.send_mail(sender = sender,
                    to = user_email,
                    subject = "CloudMania Verification mail",
                    body="""
                        Dear User:
                        Hello, Thank you for registering in cloudmania.
                        Please tap the following link to complete the email registration process.
                        http://cloud-mania.appspot.com/verify?uuid=%s#banner\n\n""" % (user_uuid))
     self.redirect('/login#banner')
     return
   else:
     errors = []
     if(total !=0):
       errors.append("Email address already exists!")
     elif(user_email or utils.valid_email(user_email)):
       errors.append("Email Address is not valid!")
     if(user_password != user_cpassword):
     	errors.append("Password and Confirm password doesn't match!")
   template_values = {"errors": "<br/>".join(errors)}
   showIndex(self, template_values)
Exemplo n.º 3
0
 def test_valid_email(self):
     from utils import valid_email
     self.assertTrue(valid_email('*****@*****.**'))
     self.assertTrue(valid_email("peter'*****@*****.**"))
     
     self.assertTrue(not valid_email('peterbe @gmail.com'))
     self.assertTrue(not valid_email("peter'be@gmai"))
Exemplo n.º 4
0
def parse_email_line(es):
    """ find all email addresses in the string 'es'.
    For example, if the input is 'Peter <*****@*****.**>'
    then return ['*****@*****.**']
    In other words, strip out all junk that isn't valid email addresses.
    """

    real_emails = []
    sep = ','
    local_domain_email_regex = re.compile(r'\b\w+@\w+\b')

    for chunk in [
            x.strip() for x in es.replace(';', ',').split(',') if x.strip()
    ]:

        # if the chunk is something like this:
        # 'SnapExpense [email protected] <*****@*****.**>'
        # then we want to favor the part in <...>
        found = re.findall('<([^@]+@[^@]+)>', chunk)
        if found:
            chunk = found[0].strip()

        if valid_email(chunk) or local_domain_email_regex.findall(chunk):
            if chunk.lower() not in [x.lower() for x in real_emails]:
                real_emails.append(chunk)

    return real_emails
Exemplo n.º 5
0
    def post(self):
        """
        Redirect to welcome page if form is valid else shows form 
        with error details
        """
        have_error = False
        self.username = self.request.get('username')
        self.password = self.request.get('password')
        self.verify = self.request.get('verify')
        self.email = self.request.get('email')
        params = dict(username=self.username, email=self.email)

        if not utils.valid_username(self.username):
            params['error_username'] = "******"
            have_error = True
        if not utils.valid_password(self.password):
            params['error_password'] = "******"
            have_error = True
        elif self.password != self.verify:
            params['error_verify'] = "Your passwords didn't match."
            have_error = True
        if not utils.valid_email(self.email):
            params['error_email'] = "That's not a valid email."
            have_error = True
        if have_error:
            self.render('register.html', **params)
        else:
            self.done()
Exemplo n.º 6
0
    def post(self):
        """
        Redirect to welcome page if form is valid else shows form 
        with error details
        """
        have_error = False
        self.username = self.request.get('username')
        self.password = self.request.get('password')
        self.verify = self.request.get('verify')
        self.email = self.request.get('email')
        params = dict(username=self.username, email=self.email)

        if not utils.valid_username(self.username):
            params['error_username'] = "******"
            have_error = True
        if not utils.valid_password(self.password):
            params['error_password'] = "******"
            have_error = True
        elif self.password != self.verify:
            params['error_verify'] = "Your passwords didn't match."
            have_error = True
        if not utils.valid_email(self.email):
            params['error_email'] = "That's not a valid email."
            have_error = True
        if have_error:
            self.render('signup-form.html', **params)
        else:
            self.done()
Exemplo n.º 7
0
    def post(self):
        logging.info(self.request.path)
        have_error = False
        self.username = self.request.get('username')
        self.password = self.request.get('password')
        self.verify = self.request.get('verify')
        self.email = self.request.get('email')

        params = dict(username=self.username, email=self.email)

        if not utils.valid_username(self.username):
            params['error_username'] = "******"
            have_error = True

        if not utils.valid_password(self.password):
            params['error_password'] = "******"
            have_error = True
        elif self.password != self.verify:
            params['error_password'] = "******"
            have_error = True

        if not utils.valid_email(self.email):
            params['error_email'] = "That's not a valid email."
            have_error = True

        if have_error:
            self.render('signup-form.html', **params)
        else:
            self.done()
Exemplo n.º 8
0
def parse_email_line(es):
    """ find all email addresses in the string 'es'.
    For example, if the input is 'Peter <*****@*****.**>'
    then return ['*****@*****.**']
    In other words, strip out all junk that isn't valid email addresses.
    """
            
    real_emails = []
    sep = ','
    local_domain_email_regex = re.compile(r'\b\w+@\w+\b')

    for chunk in [x.strip() for x in es.replace(';',',').split(',') if x.strip()]:

        # if the chunk is something like this:
        # 'SnapExpense [email protected] <*****@*****.**>'
        # then we want to favor the part in <...>
        found = re.findall('<([^@]+@[^@]+)>', chunk)
        if found:
            chunk = found[0].strip()

        if valid_email(chunk) or local_domain_email_regex.findall(chunk):
            if chunk.lower() not in [x.lower() for x in real_emails]:
                real_emails.append(chunk)

    return real_emails
Exemplo n.º 9
0
    def post(self):
        have_error = False
        self.username = self.request.get('username')
        self.password = self.request.get('password')
        self.verify = self.request.get('verify')
        self.email = self.request.get('email')

        params = dict(username = self.username,
                      email = self.email)

        if not utils.valid_username(self.username):
            params['error_username'] = "******"
            have_error = True

        if not utils.valid_password(self.password):
            params['error_password'] = "******"
            have_error = True
        elif self.password != self.verify:
            params['error_verify'] = "Your passwords didn't match."
            have_error = True

        if not utils.valid_email(self.email):
            params['error_email'] = "That's not a valid email."
            have_error = True

        if have_error:
            self.render('signup-form.html', **params)
        else:
            self.done()
Exemplo n.º 10
0
	def post(self):
		have_error = False

		next_url = str(self.request.get('next_url'))
		if not next_url or next_url.startswith('/login'):
			next_url = '/'

		self.username = self.request.get('username')
		self.password = self.request.get('password')
		self.verify = self.request.get('verify')
		self.email = self.request.get('email')

		params = dict(username = self.username,
					  email = self.email)

		if not utils.valid_username(self.username):
			params['error_username'] = "******"
			have_error = True

		if not utils.valid_password(self.password):
			params['error_password'] = "******"
			have_error = True
		elif self.password != self.verify:
			params['error_verify'] = "Your passwords didn't match."
			have_error = True

		if not utils.valid_email(self.email):
			params['error_email'] = "That's not a valid email."
			have_error = True

		if have_error:
			self.render('wiki_signup.html', **params)
		else:
			self.done()
Exemplo n.º 11
0
    def post(self):
        input_username = self.request.get("username")
        input_password = self.request.get("password")
        input_verify = self.request.get("verify")
        input_email = self.request.get("email")

        valid_username = u4.valid_username(input_username)
        valid_password = u4.valid_password(input_password)
        valid_verify = u4.valid_verify(input_password, input_verify)
        valid_email =  u4.valid_email(input_email)

        errors = ["", "", "", ""]

        if not valid_username:
            errors[0] = "That's not a valid username."
        if not valid_password:
            errors[1] = "That wasn't a valid password."
        if not valid_verify:
            errors[2] = "Your passwords didn't match."
        if not valid_email and input_email != "":
            errors[3] = "That's not a valid email."
        
        if errors != ["", "", "", ""]:
            self.write_form(errors, input_username, "", "", input_email)
        else:  
            user_existence = User.all().filter('username =', input_username).get()
            if user_existence:
                errors[0] = "That user already exists."
                self.write_form(errors, input_username, "", "", input_email)
            else:
                hashed_pw = u4.make_pw_hash(str(input_username), str(input_password))
                u= User(username=str(input_username), hashed_pw=hashed_pw, email=str(input_email))
                u.put()
                self.login(username=str(input_username), secret=secret)
                self.redirect("/welcome")
Exemplo n.º 12
0
    def post(self):
        have_error = False
        if not self.valid_form():
            have_error = True


        self.username = self.request.get('username')
        self.password = self.request.get('password')
        self.verify = self.request.get('verify')
        self.email = self.request.get('email')

        params = dict(username = self.username,
                      email = self.email)

        if not utils.valid_username(self.username):
            params['error_username'] = u"Neplatné uživatelské jméno."
            have_error = True

        if not utils.valid_password(self.password):
            params['error_password'] = u"Neplatné uživatelské heslo."
            have_error = True
        elif self.password != self.verify:
            params['error_verify'] = u"Hesla se neshodují."
            have_error = True

        if not utils.valid_email(self.email):
            params['error_email'] = u"Toto není platná emailová adresa."
            have_error = True

        if have_error:
            self.render('signup-form.html', **params)
        else:
            self.done()
Exemplo n.º 13
0
    def post(self, name):
        username = self.request.get("username")
        password = self.request.get("password")
        vpass = self.request.get("vpass")
        email = self.request.get("email")

        have_error = False;
        words={"username": username, "email":email}

        if not utils.valid_username(username):
            words["error_msg_user"] = "******"
            have_error = True
        if not utils.valid_password(password):
            words["error_msg_pass"] = "******"
            have_error = True
        if password!=vpass:
            words["error_msg_vpass"] = "******"
            have_error = True
        if not utils.valid_email(email):
            words["error_msg_email"] = "That is not a valid email address"
            have_error=True

        if have_error:
            self.render("signup.html", **words)
        else:
            # check if users already exist
            if Users.by_name(username):
                words["error_msg_user"] = "******"
                self.render("signup.html", **words)
            else:
                u = Users.create(username, password, email)
                u.put()
                self.set_secure_cookie('User-id', str(u.key().id()))
                self.redirect(name)
Exemplo n.º 14
0
  def post(self):
    errors = []
    user_email = self.request.get('email')
    is_valid = utils.valid_email(user_email)
    user_all = database.User.all().filter("email =", user_email)
    total = user_all.count(limit=1)
    if (total == 0):
      errors.append('email-id not registered!')
      template_values = {'errors': '<br/>'.join(errors), 'forgot': True}
    elif (not is_valid):
      errors.append('Wrong email-id!')
      template_values = {'errors': '<br/>'.join(errors), 'forgot': True}
    else:
      user_uuid = str(uuid.uuid1())
      database.Forgot(user=user_all.get(), uuid=user_uuid).put()
      mail.send_mail(sender='*****@*****.**',
              to = user_email,
              subject="CloudMania Reset Password",
              body="""
    Dear User,

    Hello, Please tap the following link to change password.
    http://cloud-mania.appspot.com/reset?uuid=%s#banner\n\n""" % (user_uuid))
      template_values = {'message': True}
    template_values = {'errors': '<br/>'.join(errors), 'forgot': True, 'message': True}
    showIndex(self, template_values)
Exemplo n.º 15
0
  def post(self):
    user_email = self.session.get('user')
    user_obj = getUser(user_email)
    errors = []
    success = []
    user_name = self.request.get('name', '')
    user_email = self.request.get('email', '')
    user_message = self.request.get('message', '')
    if(not (user_email and utils.valid_email(user_email) and user_name and user_message)):
      errors.append("Email Address is not valid!")
      self.redirect('/contact#contactus')
    else:
      admin = '*****@*****.**'
      mail.send_mail(sender = admin,
              to = admin,
              subject="CloudMania Query",
              body="""
    Dear Admin,

    Name = %s,
    Email = %s,
    Message = %s"""% (user_name, user_email, user_message))
      success.append("Email sent!")
      if (user_obj):
        self.redirect('/home#banner')
      else:
        self.redirect('/login#banner')
      self.redirect('/home#banner')
    template_values = {'success': '<br/>'.join(success), 'errors': '<br/>'.join(errors)}
    showIndex(self, template_values)
Exemplo n.º 16
0
 def post(self):
     username = self.request.get('username')
     password = self.request.get('password')
     verify = self.request.get('verify')
     email = self.request.get('email')
     user = User.by_name(username)
     values = {}
     if not u.valid_username(username):
         values['error_username'] = "******"
     if user:
         values['error_username2'] = "Username already exists."
     if not u.valid_password(password):
         values['error_password'] = "******"
     if password != verify:
         values['error_verify'] = "Your passwords didn't match."
     if not u.valid_email(email):
         values['error_email'] = "That's not a valid email."
     if values:
         values.update({'username' : username, 'email' : email})
         self.markup('signup.html', **values)
     else:
         password_hashed = u.make_password_hash(username, password)
         user = User(username = username, password_hashed = password_hashed, email = email)
         user.put()
         self.set_cookie("user_id", str(user.key().id()))
         self.redirect("/dashboard")
Exemplo n.º 17
0
    def validateFields(self):
        validation = {'valid': True}
        email = self.request.get('fields.email')
        password = self.request.get('fields.password')      
        fields = {'email' : email}
        errors = {}
        validation['fields'] = fields              
                      
        if not utils.valid_email(email):
            errors['error_email'] = "That's not a valid email."
            validation['valid'] = False
            validation['errors'] = errors
            return validation    
            

        if not utils.valid_password(password):
            errors['error_password'] = "******"
            validation['valid'] = False
            validation['errors'] = errors
            return validation    

        userQuery = self.validateUser(fields,password)
        if not userQuery['userFound']:
            errors['error_db'] = "Invalid email/password"
            validation['valid'] = False
            validation['errors'] = errors
            return validation


        validation['errors'] = errors
        validation['fields']['userId'] = userQuery['userId']

        return validation 
Exemplo n.º 18
0
	def post(self):
		#next_url = str(self.request.get('next_url'))
		#if not next_url or next_url.startswith('/login'):
			#next_url = '/'

		username = self.request.get('username')
		password = self.request.get('password')
		verify = self.request.get('verify')
		email = self.request.get('email')

		valid_user = utils.valid_username(username)
		valid_pass = utils.valid_password(password)
		passwords_match = utils.verify_password(password, verify)
		email_valid = utils.valid_email(email)

		params = dict(valid_user = valid_user, valid_pass = valid_pass, 
			passwords_match = passwords_match, email_valid = email_valid)
 
 		errors = set_errors(params)

		if not errors:
			user_exists = db.GqlQuery("SELECT * FROM User WHERE name = :1", username).get()
			if not user_exists:
				new_user = User(name = username, password = utils.make_pw_hash(username, password), email = email)
				new_user.put()
				self.login(new_user)
				self.redirect('/wiki') # CHANGE THIS!!!
			else:
				error_user = "******"
				self.render("signup.html", error_user = error_user)	
		else:
			self.render("signup.html", username=username, email=email, **errors)
Exemplo n.º 19
0
 def post(self):
     username = self.request.get('username')
     password = self.request.get('password')
     verify = self.request.get('verify')
     email = self.request.get('email')
     if not utils.valid_username(username) or not utils.valid_password(password) or (not utils.valid_email(email) and "" != email) or password != verify:
         errorUsername = ""
         errorPassword = ""
         errorVerify = ""
         errorEmail = ""
         if not utils.valid_username(username):
             errorUsername = "******"
         if not utils.valid_password(password):
             errorPassword = "******"
         if not utils.valid_email(email) and "" != email:
             errorEmail = "That's not a valid email."
         if password != verify:
             errorVerify = "Your passwords didn't match."
         self.render('signup.html',errorUsername=errorUsername,errorPassword=errorPassword,errorVerify=errorVerify,errorEmail=errorEmail, username=username, email=email)
     else:
         if not model.User.by_name(username):
             user = model.User.save_user(username,password)
             self.set_secure_cookie('user_id',str(user.key().id()))
             self.redirect('/')
         else:
             errorUsername = '******'
             self.render('signup.html',errorUsername=errorUsername)
Exemplo n.º 20
0
 def test_valid_email_valid(self):
     email = '*****@*****.**'
     is_valid = utils.valid_email(email)
     query = ExploriumDbApi.USERS_TABLE.select().where(ExploriumDbApi.USERS_TABLE.c.email == email)
     email_check = ExploriumDbApi.conn.execute(query).fetchone()
     if email_check:
         self.assertFalse(is_valid)
     else:
         self.assertTrue(is_valid)
Exemplo n.º 21
0
    def post(self):
        name = self.request.get('name')
        email = self.request.get('email')
        password = self.request.get('password')
        verify_password = self.request.get('verify_password')
        key = self.request.get('key')
        
        error = False
        error_name = ""
        error_password = ""
        error_email = ""
        error_verify = ""
        
        if not utils.valid_username(name):
            error_name="Your username needs to be between 3 and 20 characters long and only contain numbers and letters"
            error = True
            
        if not utils.valid_password(password):
            error_password="******"
            error = True
            
        if not utils.valid_email(email):
            error_email="Please type in a valid email address"
            error = True
            
        if password != verify_password:
            error_verify="Please ensure your passwords match"
            error = True
            
        if key != "Nicholas001":
            error_key="Please provide the correct key"
            error = True
        
        if not error:
            pw_hash = utils.make_pw_hash(name, password)
            user = model.User(parent=model.users_key(), name=name, email=email, pw_hash=pw_hash)
            user.put()
            self.login(user)
            self.redirect('/fileupload')
            
        else:
            js_code = "$('#register').modal('show');"
            data = {
                'error_name':error_name,
                'error_password':error_password,
                'error_email':error_email,
                'error_verify':error_verify,
                'error_key':error_key,
                'js_code':js_code
            }

            self.render('register.html', data=data)
            
            """
Exemplo n.º 22
0
    def post(self):
        user_uname = self.request.get('username')
        user_psswrd = self.request.get('password')
        user_ver = self.request.get('verify')
        user_email = self.request.get('email')

        uname = utils.valid_uname(user_uname)
        uname_ex = utils.user_exists(user_uname)
        psswrd = utils.valid_psswrd(user_psswrd)
        verified = utils.verify_psswrd(user_psswrd, user_ver)
        email = utils.valid_email(user_email)

        #Create error messages
        if not uname:
            uname_err = "That's not a valid username!"
        if uname_ex:
            uname_err = "This username already exists!"
        if not psswrd:
            psswrd_err = "That wasn't a valid password"
        if not verified:
            verify_err = "Passwords did not match"
        if not email:
            email_err = "That's not a valid email!"

        if not (uname and not uname_ex and psswrd and verified and
                (email or user_email == "")):
            #There was an error in one of the fields.
            self.render_signup(uname=cgi.escape(user_uname),
                               uname_err=uname_err,
                               psswrd_err=psswrd_err,
                               verify_err=verify_err,
                               email=cgi.escape(user_email),
                               email_err=email_err)
        else:
            #Create a new user.
            password_hash = utils.make_pw_hash(user_uname, user_psswrd)
            user = mydb.User(username=user_uname,
                             password_hash=password_hash,
                             salt=password_hash.split('|')[1],
                             email=user_email)
            user.put()
            mydb.allusers(update=True, newuser=user)
            print "added new user %s" % user.username

            #Redirect the user back to entry where they came from.
            redir = self.request.cookies.get('Location')

            if not redir:
                redir = '/'

            self.response.headers.add_header(
                'Set-Cookie', "user_id=%s;Location=%s;Path=/" %
                (utils.make_secure_val(str(user.key.id())), str(redir)))
            self.redirect(str(redir))
Exemplo n.º 23
0
    def post(self):
        self.username = self.request.get('username')
        self.password = self.request.get('password')
        self.v_password = self.request.get('verify')
        self.email = self.request.get('email')

        usererror = ''
        passerror = ''
        vpasserror = ''
        emailerror = ''

        if self.username:
            u_present = True
            if not valid_username(self.username):
                usererror = "That's not a valid username."
        else:
            usererror = "That's not a valid username."

        if self.password:
            p_present = True
            if not valid_pass(self.password):
                passerror = "That wasn't a valid password."
        else:
            passerror = "That wasn't a valid password."

        if self.v_password:
            vp_present = True
            if not valid_pass(self.v_password):
                vpasserror = "That wasn't a valid verification password."
        else:
            vpasserror = "That wasn't a valid verification password."

        if self.email:
            email_present = True
            if not valid_email(self.email):
                emailerror = "That wasn't a valid email."

        if self.password != self.v_password:
            passerror = "Passwords do not match"

        if usererror == '' and passerror == '' \
                and vpasserror == '' and emailerror == '':
            self.done()
        else:
            self.render("signup.html",
                        username=self.username,
                        usererror=usererror,
                        passerror=passerror,
                        vpasserror=vpasserror,
                        emailerror=emailerror)

        def done(self, *a, **kw):
            raise NotImplementedError
Exemplo n.º 24
0
    def post(self):
        # Get user input
        username = self.request.get('username')
        password = self.request.get('password')
        verify = self.request.get('verify')
        email = self.request.get('email')

        # Process results
        input_error = False
        user_error = ""
        passwd_error = ""
        verify_error = ""
        email_error = ""
        if not utils.valid_username(username):
            user_error = "That's not a valid username"
            input_error = True
        if not utils.valid_password(password):
            passwd_error = "That wasn't a valid password"
            input_error = True
        elif password != verify:
            verify_error = "Your passwords didn't match"
            input_error = True
        if not utils.valid_email(email):
            email_error = "That's not a valid email"
            input_error = True

        # Check if this user is already in our registry
        if not input_error and User.by_name(username):
            user_error = "The user already exists"
            input_error = True

        if not input_error:
            # Create user entry in database
            hashed_pw = utils.make_pw_hash(username, password)
            u = User(name=username, hashed_pw=hashed_pw, email=email)
            u.put()
            # Set cookie to user_id
            uid = u.key().id()
            user_id = utils.make_secure_cookie(str(uid))
            self.response.headers.add_header('Set-Cookie',
                                             'user_id=%s; Path=/' % user_id)
            # Redirect to welcome page
            self.redirect('/blog/welcome')
        else:
            self.render('signup.html',
                        username=username,
                        email=email,
                        user_error=user_error,
                        passwd_error=passwd_error,
                        verify_error=verify_error,
                        email_error=email_error)
Exemplo n.º 25
0
def create_user(request):
    """
    Create PINNA user
    """
    display_name = request.DATA.get('display_name', '').strip()
    email = request.DATA.get('email', '').strip()
    password = request.DATA.get('password', '').strip()

    if (not display_name) or (not email) or (not password):
        msg = 'These fields must not be empty: '

        empty_fields = []

        if not display_name:
           empty_fields.append('display_name')

        if not email:
            empty_fields.append('email')

        if not password:
            empty_fields.append('password')

        msg += ",".join(empty_fields)

        return utils.failed_response(msg, 'empty_fields')

    if not utils.valid_email(email):
        msg = "The email is invalid"
        msg_code = "email_invalid"
        return utils.failed_response(msg, msg_code)

    try:
        checked = User.objects.get(username=email)
        msg =  'The user is existed'
        return utils.failed_response(msg, "user_existed")
    except User.DoesNotExist:
        display_name = display_name.lower().title()

        user = User.objects.create_user(email, email, password,
                                        first_name=display_name)

        # Create My Tracks and My Library
        mylib = Library.objects.create()
        Profile.objects.create(user=user, mylibrary=mylib)

        session = PinnaSession.objects.create(user=user)

        msg = 'The user %s is created successfully' %display_name
        return utils.successful_response(msg, "ok",
                                         token=session.key,
                                         userid=user.pk)
Exemplo n.º 26
0
def signup(request):
	context = {}
	isVal = False 		# UGH SO INELEGANT 
	exists = False 		# UGH AGAIN
	if request.method == 'POST':
		first_name = request.POST['first_name']
		last_name = request.POST['last_name']
		email = request.POST['email']
		password = request.POST['password']

		exists = email_exists(email)
		if exists:
			context["failure_message"] = "Email already exists."
			return render(request, 'home.html', context)
		isVal = valid_email(email)
Exemplo n.º 27
0
    def validateFields(self):
        validation = {'valid': True}
        username = self.request.get('fields.username')
        password = self.request.get('fields.password')
        verifyPass = self.request.get('fields.verifyPass')
        email = self.request.get('fields.email')      
        fields = {'username':username,
                  'password':password,
                  'verifyPass':verifyPass,
                  'email':email}
        errors = {}
        validation['fields']=fields              
        user  = self.validateUser(fields)
        if  user['userFound']:
            validation['valid'] = False
            errors['error_email'] = "This email is already registered"
            validation['errors'] = errors
            return validation


        if not utils.valid_email(email):
            validation['valid'] = False
            errors['error_email'] = "That's not a valid email."
            validation['errors'] = errors
            return validation  
 

        if not utils.valid_username(username):
            validation['valid'] = False
            errors['error_username'] = "******"
            validation['errors'] = errors
            return validation  
    
        if not utils.valid_password(password):
            validation['valid'] = False
            errors['error_password'] = "******"
            validation['errors'] = errors
            return validation  

        elif verifyPass != password:
            validation['valid'] = False
            errors['error_verify'] = "Passwords do not match"
            validation['errors'] = errors
            return validation  

            
        validation['errors'] = errors
        return validation  
Exemplo n.º 28
0
    def post(self):
        valid_cookie = self.request.cookies.get("user_id")
        if valid_cookie:
            import globals

            if globals.users != None:

                has_error = False
                user_input = self.request.get("username")
                password_input = self.request.get("password")
                verify_input = self.request.get("verify")
                email_input = self.request.get("email")
                valid_u = utils.valid_username(user_input)
                valid_p = utils.valid_password(password_input)
                valid_e = utils.valid_email(email_input)
                user_error = ""
                pass_error = ""
                email_error = ""
                verify_error = ""

                if not valid_u:
                    user_error = "Invalid username, please try again."
                    has_error = True
                if not valid_p:
                    pass_error = "Invalid password, please try again."
                    has_error = True
                if password_input != verify_input:
                    verify_error = "Passwords do not match, try again."
                    has_error = True
                if not valid_e and email_input != "":
                    email_error = "Invalid email, please try again."
                    has_error = True
                if has_error != False:
                    self.render(
                        "signup.html",
                        error_user=user_error,
                        error_pass=pass_error,
                        error_verify=verify_error,
                        error_email=email_error,
                        username=user_input,
                        email=email_input,
                        user=globals.users,
                    )
                else:
                    self.redirect("/unit2/welcome?username="******"/")
Exemplo n.º 29
0
    def post(self):
        user_name = self.request.get('username')
        user_password = self.request.get('password')
        user_verify = self.request.get('verify')
        user_email = self.request.get('email')

        name = utils.valid_username(user_name)
        password = utils.valid_password(user_password)
        verify = utils.valid_verify(user_verify, user_password)
        email = utils.valid_email(user_email)

        nameerror = passworderror = verifyerror = emailerror = ""

        if not name:
            nameerror = "That's not a valid username"

        if not password:
            passworderror = "That's not a valid password"

        if password and not verify:
            verifyerror = "Your passwords didn't match"

        if user_email and not email:
            emailerror = "That's not a valid email"

        if (not (name and password and verify)) or (user_email and not email):
            self.render_signup(user_name, nameerror, passworderror,
                               verifyerror, user_email, emailerror)
        else:
            # lookup user
            u = User.gql("WHERE username = '******'" % user_name).get()

            # If user already exists
            if u:
                nameerror = "That user already exists"
                self.render_signup(user_name, nameerror, passworderror,
                                   verifyerror, user_email, emailerror)
            else:
                # make salted password hash
                h = utils.make_pw_hash(user_name, user_password)
                u = User(username=user_name, password=h)
                u.put()
                user_id = u.key().id()
                uid_cookie = str(self.put_user_id_cookie(user_id, h))
                self.response.headers.add_header(
                    "Set-Cookie", "user_id=%s; Path=/" % uid_cookie)
                self.redirect("/")
Exemplo n.º 30
0
    def post(self):
        user_name     = self.request.get('username')
        user_password = self.request.get('password')
        user_verify   = self.request.get('verify')
        user_email    = self.request.get('email')

        name     = utils.valid_username(user_name)
        password = utils.valid_password(user_password)
        verify   = utils.valid_verify(user_verify, user_password)
        email    = utils.valid_email(user_email)

        nameerror = passworderror = verifyerror = emailerror = ""

        if not name:
            nameerror = "That's not a valid username"

        if not password:
            passworderror = "That's not a valid password"

        if password and not verify:
            verifyerror = "Your passwords didn't match"

        if user_email and not email:
            emailerror = "That's not a valid email"

        if (not (name and password and verify)) or (user_email and not email):
            self.render_signup(user_name, nameerror, passworderror, 
                               verifyerror, user_email, emailerror)
        else:
            # lookup user
            u = User.gql("WHERE username = '******'"%user_name).get()

            # If user already exists
            if u:
                nameerror = "That user already exists"
                self.render_signup(user_name, nameerror, passworderror, 
                                   verifyerror, user_email, emailerror)		
            else:
                # make salted password hash
                h = utils.make_pw_hash(user_name, user_password)
                u = User(username=user_name, password=h)
                u.put()
                user_id = u.key().id()
                uid_cookie = str(self.put_user_id_cookie(user_id, h))
                self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/"%uid_cookie)
                self.redirect("/")
Exemplo n.º 31
0
    def change_user_email():
        if not is_admin(request):
            return 'unauthorized', 403

        body = request.json

        # Validations
        if not type_check(body, 'dict'):
            return 'body must be an object', 400
        if not object_check(body, 'username', 'str'):
            return 'body.username must be a string', 400
        if not object_check(body, 'email', 'str'):
            return 'body.email must be a string', 400
        if not valid_email(body['email']):
            return 'email must be a valid email', 400

        user = db_get('users', {'username': body['username'].strip().lower()})

        if not user:
            return 'invalid username', 400

        token = make_salt()
        hashed_token = hash(token, make_salt())

        # We assume that this email is not in use by any other users. In other words, we trust the admin to enter a valid, not yet used email address.
        db_update(
            'users', {
                'username': user['username'],
                'email': body['email'],
                'verification_pending': hashed_token
            })

        # If this is an e2e test, we return the email verification token directly instead of emailing it.
        if is_testing_request(request):
            resp = {'username': user['username'], 'token': hashed_token}
        else:
            send_email_template(
                'welcome_verify', body['email'], requested_lang(),
                os.getenv('BASE_URL') + '/auth/verify?username='******'username']) + '&token=' +
                urllib.parse.quote_plus(hashed_token))

        return '', 200
Exemplo n.º 32
0
    def signIn(self, request):
        """ This function register a new user as player.
        Input: A unique username and email address"""
        username = request.username
        email = request.email
        if not utils.valid_username(username) or not utils.valid_email(email):
            raise endpoints.ConflictException('Invalid Input')
        if Player.query(Player.username == request.username).get():
            raise endpoints.ConflictException(
                'A User with that name already exists!')

        Player(username=username, email=email).put()

        # create default player if not exist
        if not Player.query(Player.username == "computer").get():
            self._defaultPlayer()

        return MessageForm(message="Welcome Player %s. Enjoy racing!!!" %
                           username)
Exemplo n.º 33
0
 def post(self):
     have_error = False
     # get user input from request
     username = self.request.get('username')
     password = self.request.get('password')
     verify_password = self.request.get('verify_password')
     email = self.request.get('email')
     verify_email = self.request.get('verify_email')
     # set params to be passed back to form if error
     params = dict(username = username, email = email)
     # get users from db
     user = User.by_name(username)
     # check if username already exists, if exists return error
     if user:
         params['exist_error'] = "That username already exists!"
         have_error = True
     # check that username is valid
     if not utils.valid_username(username):
         params['error_username'] = "******"
         have_error = True
     # check that passoword is valid and passwords match
     if not utils.valid_password(password):
         params['error_password'] = "******"
         have_error = True
     elif password != verify_password:
         params['error_verify_password'] = "******"
         have_error = True
     # check that email is valid and match
     if not utils.valid_email(email):
         params['error_email'] = "That's not a valid email!"
         have_error = True
     # if there is error, rerender form with error params,
     # else redirect to main
     if have_error:
         self.render("signup.html", **params)
     else:
         # store in User table
         u = User.register(username, password, email)
         u.put()
         # set secure cookie
         self.login(u)
         self.redirect('/')
Exemplo n.º 34
0
    def change_user_email():
        user = current_user()
        if not is_admin(user):
            return 'unauthorized', 403

        body = request.json

        # Validations
        if not isinstance(body, dict):
            return 'body must be an object', 400
        if not isinstance(body.get('username'), str):
            return 'body.username must be a string', 400
        if not isinstance(body.get('email'), str):
            return 'body.email must be a string', 400
        if not valid_email(body['email']):
            return 'email must be a valid email', 400

        user = DATABASE.user_by_username(body['username'].strip().lower())

        if not user:
            return 'invalid username', 400

        token = make_salt()
        hashed_token = hash(token, make_salt())

        # We assume that this email is not in use by any other users. In other words, we trust the admin to enter a valid, not yet used email address.
        DATABASE.update_user(user['username'], {
            'email': body['email'],
            'verification_pending': hashed_token
        })

        # If this is an e2e test, we return the email verification token directly instead of emailing it.
        if is_testing_request(request):
            resp = {'username': user['username'], 'token': hashed_token}
        else:
            send_email_template(
                'welcome_verify', body['email'],
                email_base_url() + '/auth/verify?username='******'username']) + '&token=' +
                urllib.parse.quote_plus(hashed_token))

        return '', 200
Exemplo n.º 35
0
def validate_form(signup, input_username, input_password, input_verify=None, input_email=None):
    """
    params: 
     - signup: true for signup validation, false for login validation  
     - username and password
     - input_verify, input_email: optional parameters
    returns: 
      - returns true if input is valid, false otherwise and
      - dictionary (params) of errors
    """

    params = {}
    valid_input = True

    valid_username = utils.valid_username(input_username)
    if not valid_username:
        valid_input = False
        params['error_username'] = "******"

    valid_password = utils.valid_password(input_password)
    if not valid_password:
        valid_input = False
        params['error_password'] = "******"

    if not input_verify and signup:
        valid_input = False
        params['error_verify'] = "verify password"        

    if input_verify and signup:
        valid_verify = utils.valid_password(input_verify)
        if input_password != input_verify:
            valid_input = False
            params['error_verify'] = "Password and Verification do not match"

    if input_email and signup:
        valid_email = utils.valid_email(input_email)
        if not valid_email:
                params['error_email'] = "Invalid email address"
                params['return_email'] = input_email

    return valid_input, params       
Exemplo n.º 36
0
    def post(self):
        user_uname = self.request.get('username')
        user_psswrd = self.request.get('password')
        user_ver = self.request.get('verify')
        user_email = self.request.get('email')

        uname = utils.valid_uname(user_uname)
        uname_ex = utils.user_exists(user_uname)
        psswrd = utils.valid_psswrd(user_psswrd)
        verified = utils.verify_psswrd(user_psswrd, user_ver)
        email = utils.valid_email(user_email)

        # this will store the values to be returned
        ret = {"uname":cgi.escape(user_uname), "uname_err":"", "psswrd_err":"", "verify_err":"", "email":cgi.escape(user_email), "email_err":""}

        if not uname:
            ret["uname_err"] = "That's not a valid username!"
        if uname_ex:
            ret["uname_err"] = "This username already exists!"
        if not psswrd:
            ret["psswrd_err"] = "That wasn't a valid password"
        if not verified:
            ret["verify_err"] = "Passwords did not match"
        if not email:
            ret["email_err"] = "That's not a valid email!"

        if not(uname and not uname_ex and psswrd and verified and (email or user_email == "")):
            self.render_signup(uname=ret["uname"], uname_err=ret["uname_err"], psswrd_err=ret["psswrd_err"], verify_err=ret["verify_err"], email=ret["email"], email_err=ret["email_err"])
        else:
            password_hash = utils.make_pw_hash(user_uname, user_psswrd)
            user = mydb.User(username=user_uname, password_hash=password_hash, salt=password_hash.split('|')[1], email=user_email)
            user.put()
            print "added new user %s" % user.username
            mydb.allusers(True, user)
            redir = self.request.cookies.get('Location')
            #time.sleep(1)
            if not redir:
                redir = '/'
            self.response.headers.add_header('Set-Cookie', "user_id=%s;Location=%s;Path=/" % (utils.make_secure_val(str(user.key().id())), str(redir)))
            print redir
            self.redirect(str(redir))
Exemplo n.º 37
0
def signup():
    ref = request
    if request.method == 'POST':
        try:
            username = request.form.get('user_username')
            email = request.form.get('user_email')
            password = utils.hash_password(request.form.get('user_password'))
            firstname = request.form.get('user_firstname')
            lastname = request.form.get('user_lastname')
            repeat_password = utils.hash_password(request.form.get('user_repeat_password'))
            if password != repeat_password:
                error = " Passwords do not match ! "
                return render_template('signup.html', error=error)

            if not utils.valid_username(username):
                traceback.print_exc()
                error = " Username is already taken "
                return render_template('signup.html', error=error)

            if not utils.valid_email(email):
                traceback.print_exc()
                p = re.compile('[aA0-zZ9$]+@[aA0-zZ9]+.[a-z]+')
                if p.match(email) is None:
                    error = " Email is already taken "
                else:
                    error = " Invalid Email"
                return render_template('signup.html', error=error)

            session['username'] = username
            # session['password'] = password
            query = ExploriumDbApi.USERS_TABLE.insert().values(username=username, password=password, email=email,
                                                               firstname=firstname, lastname=lastname)
            ExploriumDbApi.conn.execute(query)

            return render_template('index.html', this_username=session['username'], show_what="Welcome!",
                                   result_info_list='')
        except Exception as e:
            render_template('signup.html', error='Invalid Input')


    return render_template('signup.html')
Exemplo n.º 38
0
def validate_form(signup, input_username, input_password, input_verify=None, input_email=None):
    """
    params: 
     - signup: true for signup validation, false for login validation  
     - username and password
     - input_verify, input_email: optional parameters
    returns: 
      - returns true if input is valid, false otherwise and
      - dictionary (params) of errors
    """

    params = {}
    valid_input = True

    valid_username = utils.valid_username(input_username)
    if not valid_username:
        valid_input = False
        params['error_username'] = "******"

    valid_password = utils.valid_password(input_password)
    if not valid_password:
        valid_input = False
        params['error_password'] = "******"

    if not input_verify and signup:
        valid_input = False
        params['error_verify'] = "verify password"        

    if input_verify and signup:
        valid_verify = utils.valid_password(input_verify)
        if input_password != input_verify:
            valid_input = False
            params['error_verify'] = "Password and Verification do not match"

    if input_email and signup:
        valid_email = utils.valid_email(input_email)
        if not valid_email:
                params['error_email'] = "Invalid email address"
                params['return_email'] = input_email

    return valid_input, params
Exemplo n.º 39
0
 def post(self):
   user_email = self.request.get('email', '')
   is_valid = utils.valid_email(user_email)
   errors = []
   if (is_valid):
     user_password = self.request.get('password', '')
     user_obj = getUser(user_email)
     if (user_obj and base64.b64encode(user_password) == user_obj.password):
       template_values = {'login': True, 'user': user_obj.email}
       if(base64.b64encode(user_password) == user_obj.password):
         self.session['user'] = user_email
         logging.info("%s just logged in" % user_email)
         template_values = {'login': True, 'user': user_obj.email}
         self.redirect('/home#banner')
     else:
       errors.append('Wrong Username / Password!')
       template_values = {'errors': '<br/>'.join(errors), 'login': True}
   else:
     errors.append('Invalid Email Address!!')
     template_values = {'errors': '<br/>'.join(errors), 'login': True}
   showIndex(self, template_values)
Exemplo n.º 40
0
    def post(self):
        input_username = self.request.get("username")
        input_password = self.request.get("password")
        input_verify = self.request.get("verify")
        input_email = self.request.get("email")

        valid_username = u4.valid_username(input_username)
        valid_password = u4.valid_password(input_password)
        valid_verify = u4.valid_verify(input_password, input_verify)
        valid_email = u4.valid_email(input_email)

        errors = ["", "", "", ""]

        if not valid_username:
            errors[0] = "That's not a valid username."
        if not valid_password:
            errors[1] = "That wasn't a valid password."
        if not valid_verify:
            errors[2] = "Your passwords didn't match."
        if not valid_email and input_email != "":
            errors[3] = "That's not a valid email."

        if errors != ["", "", "", ""]:
            self.write_form(errors, input_username, "", "", input_email)
        else:
            user_existence = User.all().filter('username =',
                                               input_username).get()
            if user_existence:
                errors[0] = "That user already exists."
                self.write_form(errors, input_username, "", "", input_email)
            else:
                hashed_pw = u4.make_pw_hash(str(input_username),
                                            str(input_password))
                u = User(username=str(input_username),
                         hashed_pw=hashed_pw,
                         email=str(input_email))
                u.put()
                self.login(username=str(input_username), secret=secret)
                self.redirect("/welcome")
Exemplo n.º 41
0
 def process_form(self, post_data):
     """
     Utility function to process the form and generate errors.
     """
     username = post_data[0]
     password = post_data[1]
     verify = post_data[2]
     email = post_data[3]
     errors = {}
     if not username or not valid_username(username):
         errors['username_error'] = "That's not a valid username."
     if not password or not valid_password(password):
         errors['password_error'] = "That wasn't a valid password."
     else:
         if not verify or verify != password:
             errors['verify_error'] = "Your passwords didn't match."
     if email and not valid_email(email):
         errors['email_error'] = "That's not a valid email."
     if errors:
         errors['email'] = email
         errors['username'] = username
     return errors
Exemplo n.º 42
0
    def post(self):
        error_input = False
        username = self.request.get('username')
        password = self.request.get('password')
        verify = self.request.get('verify')
        email = self.request.get('email')

        params = dict(username=username, email=email)

        if not valid_username(username):
            params['error_username'] = "******"
            error_input = True
            
        if not valid_password(password):
            params['error_password'] = "******"
            error_input = True

        elif password != verify:
            params['error_verify'] = "Your passwords do not match"
            error_input = True

        if not valid_email(email):
            params['error_email'] = "That's not a valid email"
            error_input = True

        if error_input:
            self.render('signup_page.html', **params)
        else:
            user = User.find_by_name(username)
            
            if user:
                params['error_username'] = "******"
                self.render('signup_page.html', **params)
            else:
                user = User.register(username, password, email)
                user.put()

                self.login(user)
                self.redirect('/home')
Exemplo n.º 43
0
    def post(self):
        error_input = False
        username = self.request.get('username')
        password = self.request.get('password')
        verify = self.request.get('verify')
        email = self.request.get('email')

        params = dict(username=username, email=email)

        if not valid_username(username):
            params['error_username'] = "******"
            error_input = True

        if not valid_password(password):
            params['error_password'] = "******"
            error_input = True

        elif password != verify:
            params['error_verify'] = "Your passwords do not match"
            error_input = True

        if not valid_email(email):
            params['error_email'] = "That's not a valid email"
            error_input = True

        if error_input:
            self.render('signup_page.html', **params)
        else:
            user = User.find_by_name(username)

            if user:
                params['error_username'] = "******"
                self.render('signup_page.html', **params)
            else:
                user = User.register(username, password, email)
                user.put()

                self.login(user)
                self.redirect('/home')
Exemplo n.º 44
0
    def post(self):
        if self.user:
            self.session.add_flash("You are already logged in")
            self.redirect('/')
        else:
            self.username = self.request.get('username')
            self.password = self.request.get('password')
            self.confirm = self.request.get('confirm')
            self.email = self.request.get('email')

            params = dict(username=self.username,
                          email=self.email)
            have_error = False
            if not valid_username(self.username):
                params['error_username'] = '******'
                have_error = True
            elif User.user_by_name(self.username):
                params['error_username'] = '******'
                have_error = True
            if not valid_password(self.password):
                params['error_password'] = '******'
                have_error = True
            elif self.password != self.confirm:
                params['error_confirm'] = 'Passwords do not match'
                have_error = True
            if not valid_email(self.email):
                params['error_email'] = 'Invalid email'
                have_error = True

            if have_error:
                self.render('registration.html', **params)
            else:
                user = User.register_user(username=self.username,
                                          password=self.password,
                                          email=self.email)
                user.put()
                self.login(user)
                self.session.add_flash("Welcome, %s!" % user.username)
                self.redirect('/')
Exemplo n.º 45
0
    def post(self):
        error_username = ''
        error_password = ''
        error_verify = ''
        error_email=''
        username = self.request.get('username')
        password = self.request.get('password')
        verify = self.request.get('verify')
        email = self.request.get('email')
        
        if (valid_user(username) and valid_password(password) and valid_verify(verify,password)) and ((valid_email(email) or email=='')):
            user1 = db.GqlQuery('SELECT * FROM User WHERE username = :1', username)# see if username already exists
            user2 = db.GqlQuery('SELECT * FROM User WHERE email = :1', email)# see if email already exists
            if not (user1.get() and user2.get()):                     
                new_user = User(username = username, password = make_pw_hash(username, password), email = email)
                new_user.put()
                user_id = new_user.key().id()              
                self.response.headers.add_header('Set-Cookie', 'user_id = %s' %user_id)#set cookie
                self.redirect('/welcome')
            else:
                if user1.get():
			        error_username = '******'
                if user2.get():
                    error_email = 'Email already exists!'
                self.render('signup.html',username=username, password=password, verify=verify, email=email, error_username=error_username, error_password=error_password, error_verify=error_verify, error_email=error_email)					
                    
            
        else:
            if not valid_user(username):
			    error_username = "******"
            if not valid_password(password):
                error_password = "******"
            if not valid_verify(verify,password) or not(password and verify):
                error_verify = "Your passwords didn't match "
            if not (valid_email(email) or email == ''):
                error_email = "That's not a valid email!"
			
            self.render('signup.html', username=username, password=password, verify=verify, email=email, error_username=error_username, error_password=error_password, error_verify=error_verify, error_email=error_email)
Exemplo n.º 46
0
    def post(self):
        username = self.request.get("username")
        password = self.request.get("password")
        verify = self.request.get("verify")
        email = self.request.get("email")

        username_error = ""
        password_error = ""
        verify_error = ""
        email_error = ""

        if not utils.valid_username(username):
            username_error = "That's not a valid username."
        elif db.GqlQuery("SELECT * FROM User WHERE username = '******'" %
                username).count() != 0:
            username_error = "Username already exists."

        if utils.valid_password(password):
            if not password == verify:
                verify_error = "Your passwords didn't match."
        else:
            password_error = "That wasn't a valid password."

        if not utils.valid_email(email):
            email_error = "That's not a valid email."

        if (username_error != "" or password_error != "" or
            verify_error != "" or email_error != ""):
            self.write_form([username, username_error], password_error,
                            verify_error, [email, email_error])
        else:
            user = models.User(username=username,
                               hashed_pw=utils.make_pw_hash(username, password),
                               email=email)
            user.put()
            self.response.headers.add_header('Set-Cookie', str('user-id=%s; Path=/'
                                     % utils.make_secure_val(utils.SECRET, username)))
            self.redirect("/blog/welcome")
Exemplo n.º 47
0
  def post(self):
    have_error = False
    self.username = self.request.get('username')
    self.password = self.request.get('password')
    self.verify = self.request.get('verify')
    self.email = self.request.get('email')
    
    params = dict(username = self.username,
                      email = self.email)
    
    if not valid_username(self.username):
        params['error_username'] = "******"
        have_error = True

    u = User.by_name(self.username)
    if u:
        params['error_username'] = "******"
        have_error = True
    
    if not valid_password(self.password):
        params['error_password'] = "******"
        have_error = True
    elif self.password != self.verify:
        params['error_verify'] = "Your passwords didn't match."
        have_error = True
    
    if not valid_email(self.email):
        params['error_email'] = "that's not a valid email"
        have_error = True
    
    if have_error:
        self.render('signup-form.html', **params)
    else:
        u = User.register(self.username, self.password, self.email)
        u.put()
                
        self.site_login(u)
        self.redirect('/blog/welcome') #?username=' + username)
    def post(self):
        have_error = False
        self.username = self.request.get('username')
        self.password = self.request.get('password')
        self.verify = self.request.get('verify')
        self.email = self.request.get('email')
        params = dict(username=self.username, email=self.email)

        if not utils.valid_username(self.username):
            params['error_username'] = "******"
            have_error = True
        if not utils.valid_password(self.password):
            params['error_password'] = "******"
            have_error = True
        elif self.password != self.verify:
            params['error_verify'] = "Your passwords didn't match."
            have_error = True
        if not utils.valid_email(self.email):
            params['error_email'] = "That's not a valid email."
            have_error = True
        if have_error:
            self.render('register.html', **params)
        else:
            self.done()
Exemplo n.º 49
0
    def update_profile(user):

        body = request.json
        if not type_check(body, 'dict'):
            return 'body must be an object', 400
        if 'email' in body:
            if not object_check(body, 'email', 'str'):
                return 'body.email must be a string', 400
            if not valid_email(body['email']):
                return 'body.email must be a valid email', 400
        if 'country' in body:
            if not body['country'] in countries:
                return 'body.country must be a valid country', 400
        if 'birth_year' in body:
            if not object_check(
                    body, 'birth_year',
                    'int') or body['birth_year'] <= 1900 or body[
                        'birth_year'] > datetime.datetime.now().year:
                return 'birth_year must be a year between 1900 and ' + str(
                    datetime.datetime.now().year), 400
        if 'gender' in body:
            if body['gender'] != 'm' and body['gender'] != 'f' and body[
                    'gender'] != 'o':
                return 'body.gender must be m/f/o', 400

        resp = {}
        if 'email' in body:
            email = body['email'].strip().lower()
            if email != user['email']:
                exists = db_get('users', {'email': email}, True)
                if exists:
                    return 'email exists', 403
                token = make_salt()
                hashed_token = hash(token, make_salt())
                db_update(
                    'users', {
                        'username': user['username'],
                        'email': email,
                        'verification_pending': hashed_token
                    })
                # If this is an e2e test, we return the email verification token directly instead of emailing it.
                if is_testing_request(request):
                    resp = {
                        'username': user['username'],
                        'token': hashed_token
                    }
                else:
                    send_email_template(
                        'welcome_verify', email, requested_lang(),
                        os.getenv('BASE_URL') + '/auth/verify?username='******'username']) + '&token=' +
                        urllib.parse.quote_plus(hashed_token))

        if 'country' in body:
            db_update('users', {
                'username': user['username'],
                'country': body['country']
            })
        if 'birth_year' in body:
            db_update('users', {
                'username': user['username'],
                'birth_year': body['birth_year']
            })
        if 'gender' in body:
            db_update('users', {
                'username': user['username'],
                'gender': body['gender']
            })

        return jsonify(resp)
Exemplo n.º 50
0
    def post(self):
		if self.request.get('login_email') and self.request.get('login_password'):
			user_email = self.request.get('login_email')
			user_psswrd = self.request.get('login_password')

			print user_email

			valid_pwd = False
			valid_email = False

			q = mydb.User.get_by_email(user_email)
			if not(q is None):
				valid_email = True
				valid_pwd = utils.valid_pw(user_email, user_psswrd, q.password_hash)

				if valid_pwd and valid_email:
					self.response.headers.add_header('Set-Cookie', "user_id=%s;Path=/" % utils.make_secure_val(str(q.key().id())))
					self.redirect('/hello')
				else:
					self.render_signup(email=cgi.escape(user_email), login_err="Invalid username or password. Please sign up or try again.")
		else:
			user_email = self.request.get('email')
			user_psswrd = self.request.get('password')
			user_first_name = self.request.get('first_name')
			user_last_name = self.request.get('last_name')
			user_dob = self.request.get('dob')
			user_gender = self.request.get('gender')
			user_occupation = self.request.get('occupation')
			user_confirmation = self.request.get('confirmation')

			print user_email
			print user_psswrd
			print user_first_name
			print user_last_name
			print utils.convert_dob(user_dob)
			print user_gender
			print user_occupation
			print user_confirmation

			name = utils.valid_name(user_first_name) and utils.valid_name(user_last_name)
			user_ex = utils.user_exists(user_email)
			psswrd = utils.valid_psswrd(user_psswrd)
			email = utils.valid_email(user_email)

			# this will store the values to be returned
			#ret = {"uname":cgi.escape(user_uname), "uname_err":"", "psswrd_err":"", "verify_err":"", "email":cgi.escape(user_email), "email_err":""}

			if not name or user_ex or not psswrd or not email:
				input_err = "Some input was incorrect. Further details to come soon."
			if not(name and not user_ex and psswrd and email):
				self.render_signup(first_name=first_name,
				login_err=login_err,
				input_err=input_err,
				email=email,
				last_name=last_name,
				gender=gender,
				occupation=occupation)
			else:
				password_hash = utils.make_pw_hash(user_email, user_psswrd)
				user = mydb.User(first_name=user_first_name, last_name=user_last_name, dob=utils.convert_dob(user_dob), gender=user_gender, occupation=user_occupation, password_hash=password_hash, salt=password_hash.split('|')[1], email=user_email)
				user.put()
				print "added new user %s" % user.email
				#mydb.allusers(True, user)
				time.sleep(0.2)
				self.response.headers.add_header('Set-Cookie', "user_id=%s;Path=/" % utils.make_secure_val(str(user.key().id())))
				self.redirect('/hello')
Exemplo n.º 51
0
def email(email_str):
    """Return email_str if valid, raise an exception in other case."""
    if valid_email(email_str):
        return email_str
    else:
        raise ValueError('{} is not a valid email'.format(email_str))
Exemplo n.º 52
0
    def signup():
        body = request.json
        # Validations, mandatory fields
        if not type_check(body, 'dict'):
            return 'body must be an object', 400
        if not object_check(body, 'username', 'str'):
            return 'username must be a string', 400
        if '@' in body['username']:
            return 'username cannot contain an @-sign', 400
        if ':' in body['username']:
            return 'username cannot contain a colon', 400
        if len(body['username'].strip()) < 3:
            return 'username must be at least three characters long', 400
        if not object_check(body, 'password', 'str'):
            return 'password must be a string', 400
        if len(body['password']) < 6:
            return 'password must be at least six characters long', 400
        if not object_check(body, 'email', 'str'):
            return 'email must be a string', 400
        if not valid_email(body['email']):
            return 'email must be a valid email', 400
        # Validations, optional fields
        if 'country' in body:
            if not body['country'] in countries:
                return 'country must be a valid country', 400
        if 'birth_year' in body:
            if not object_check(
                    body, 'birth_year',
                    'int') or body['birth_year'] <= 1900 or body[
                        'birth_year'] > datetime.datetime.now().year:
                return 'birth_year must be a year between 1900 and ' + datetime.datetime.now(
                ).year, 400
        if 'gender' in body:
            if body['gender'] != 'm' and body['gender'] != 'f' and body[
                    'gender'] != 'o':
                return 'gender must be m/f/o', 400

        user = db_get('users', {'username': body['username'].strip().lower()})
        if user:
            return 'username exists', 403
        email = db_get('users', {'email': body['email'].strip().lower()}, True)
        if email:
            return 'email exists', 403

        hashed = hash(body['password'], make_salt())

        token = make_salt()
        hashed_token = hash(token, make_salt())
        username = body['username'].strip().lower()
        email = body['email'].strip().lower()

        if not is_testing_request(
                request) and 'subscribe' in body and body['subscribe'] == True:
            # If we have a Mailchimp API key, we use it to add the subscriber through the API
            if os.getenv('MAILCHIMP_API_KEY') and os.getenv(
                    'MAILCHIMP_AUDIENCE_ID'):
                # The first domain in the path is the server name, which is contained in the Mailchimp API key
                request_path = 'https://' + os.getenv(
                    'MAILCHIMP_API_KEY').split(
                        '-')[1] + '.api.mailchimp.com/3.0/lists/' + os.getenv(
                            'MAILCHIMP_AUDIENCE_ID') + '/members'
                request_headers = {
                    'Content-Type': 'application/json',
                    'Authorization': 'apikey ' + os.getenv('MAILCHIMP_API_KEY')
                }
                request_body = {'email_address': email, 'status': 'subscribed'}
                r = requests.post(request_path,
                                  headers=request_headers,
                                  data=json.dumps(request_body))

                subscription_error = None
                if r.status_code != 200 and r.status_code != 400:
                    subscription_error = True
                # We can get a 400 if the email is already subscribed to the list. We should ignore this error.
                if r.status_code == 400 and not re.match(
                        '.*already a list member', r.text):
                    subscription_error = True
                # If there's an error in subscription through the API, we report it to the main email address
                if subscription_error:
                    send_email(
                        config['email']['sender'],
                        'ERROR - Subscription to Hedy newsletter on signup',
                        email, '<p>' + email + '</p><pre>Status:' +
                        str(r.status_code) + '    Body:' + r.text + '</pre>')
            # Otherwise, we send an email to notify about this to the main email address
            else:
                send_email(config['email']['sender'],
                           'Subscription to Hedy newsletter on signup', email,
                           '<p>' + email + '</p>')

        user = {
            'username': username,
            'password': hashed,
            'email': email,
            'created': timems(),
            'verification_pending': hashed_token,
            'last_login': timems()
        }

        if 'country' in body:
            user['country'] = body['country']
        if 'birth_year' in body:
            user['birth_year'] = body['birth_year']
        if 'gender' in body:
            user['gender'] = body['gender']

        db_create('users', user)

        # We automatically login the user
        cookie = make_salt()
        db_create(
            'tokens', {
                'id': cookie,
                'username': user['username'],
                'ttl': times() + session_length
            })

        # If this is an e2e test, we return the email verification token directly instead of emailing it.
        if is_testing_request(request):
            resp = make_response({'username': username, 'token': hashed_token})
        # Otherwise, we send an email with a verification link and we return an empty body
        else:
            send_email_template(
                'welcome_verify', email, requested_lang(),
                os.getenv('BASE_URL') + '/auth/verify?username='******'&token=' +
                urllib.parse.quote_plus(hashed_token))
            resp = make_response({})

        # We set the cookie to expire in a year, just so that the browser won't invalidate it if the same cookie gets renewed by constant use.
        # The server will decide whether the cookie expires.
        resp.set_cookie(cookie_name,
                        value=cookie,
                        httponly=True,
                        secure=True,
                        samesite='Lax',
                        path='/',
                        max_age=365 * 24 * 60 * 60)
        return resp
Exemplo n.º 53
0
def edit_profile():
    if 'username' not in session or 'password' not in session:
        return redirect(url_for('signin'))
    if session['username'] == 'guest':
        return redirect(url_for('index'))

    if request.method == 'GET':
        if 'username' not in session:
            return redirect(url_for('signin'))
        userinfo = ExploriumDbApi.load_user_info(session['username'])
        error = ""

        return render_template('profile-edit.html', this_username=session['username'], user_info=userinfo, error=error)
    if request.method == "POST":
        try:
            if 'username' not in session:
                return redirect(url_for('signin'))
            firstname = request.form.get('user-firstname')
            lastname = request.form.get('user-lastname')
            email = request.form.get('user-email')
            username = request.form.get('user-username')

            userinfo = ExploriumDbApi.load_user_info(session['username'])

            if not firstname or not lastname or not email or not username:
                traceback.print_exc()
                error = " Fields cannot be empty. "
                return render_template('profile-edit.html', this_username=session['username'], user_info=userinfo,
                                       error=error)
            if not utils.valid_username(username) and username != userinfo['username']:
                error = " Username is already taken "
                return render_template('profile-edit.html', this_username=session['username'], user_info=userinfo,
                                           error=error)
            if not utils.valid_email(email) and email != userinfo['email']:
                p = re.compile('[aA0-zZ9$]+@[aA0-zZ9]+.[a-z]+')
                if p.match(email) is None:
                    error = " Email is already taken "
                else:
                    error = " Invalid Email"
                return render_template('profile-edit.html', this_username=session['username'], user_info=userinfo,
                                       error=error)

            session['username'] = username
            if request.form.get('user-password'):
                password = utils.hash_password(request.form.get('user-password'))
                query = ExploriumDbApi.USERS_TABLE.update().where(
                    ExploriumDbApi.USERS_TABLE.c.user_id == userinfo['user_id']).values(firstname=firstname, lastname=lastname,
                                                                                        username=username, email=email,
                                                                                        password=password)
            else:
                query = ExploriumDbApi.USERS_TABLE.update().where(
                    ExploriumDbApi.USERS_TABLE.c.user_id == userinfo['user_id']).values(firstname=firstname, lastname=lastname,
                                                                                        username=username, email=email)

            ExploriumDbApi.conn.execute(query)

            userinfo = ExploriumDbApi.load_user_info(session['username'])

            return render_template('profile.html', this_username=session['username'], user_info=userinfo)
        except:
            userinfo = ExploriumDbApi.load_user_info(session['username'])
            error = "Invalid Input"

            return render_template('profile-edit.html', this_username=session['username'], user_info=userinfo,
                                   error=error)
Exemplo n.º 54
0
 def test_valid_email_invalid(self):
     email = 'tea.com'
     is_valid = utils.valid_email(email)
     self.assertFalse(is_valid)
Exemplo n.º 55
0
    def update_profile(user):

        body = request.json
        if not isinstance(body, dict):
            return 'body must be an object', 400
        if 'email' in body:
            if not isinstance(body.get('email'), str):
                return 'body.email must be a string', 400
            if not valid_email(body['email']):
                return 'body.email must be a valid email', 400
        if 'country' in body:
            if not body['country'] in countries:
                return 'body.country must be a valid country', 400
        if 'birth_year' in body:
            if not isinstance(body.get('birth_year'),
                              int) or body['birth_year'] <= 1900 or body[
                                  'birth_year'] > datetime.datetime.now().year:
                return 'birth_year must be a year between 1900 and ' + str(
                    datetime.datetime.now().year), 400
        if 'gender' in body:
            if body['gender'] != 'm' and body['gender'] != 'f' and body[
                    'gender'] != 'o':
                return 'body.gender must be m/f/o', 400
        if 'prog_experience' in body and body['prog_experience'] not in [
                'yes', 'no'
        ]:
            return 'If present, prog_experience must be "yes" or "no"', 400
        if 'experience_languages' in body:
            if not isinstance(body['experience_languages'], list):
                return 'If present, experience_languages must be an array', 400
            for language in body['experience_languages']:
                if language not in [
                        'scratch', 'other_block', 'python', 'other_text'
                ]:
                    return 'Invalid language: ' + str(language), 400

        resp = {}
        if 'email' in body:
            email = body['email'].strip().lower()
            if email != user['email']:
                exists = DATABASE.user_by_email(email)
                if exists:
                    return 'email exists', 403
                token = make_salt()
                hashed_token = hash(token, make_salt())
                DATABASE.update_user(user['username'], {
                    'email': email,
                    'verification_pending': hashed_token
                })
                # If this is an e2e test, we return the email verification token directly instead of emailing it.
                if is_testing_request(request):
                    resp = {
                        'username': user['username'],
                        'token': hashed_token
                    }
                else:
                    send_email_template(
                        'welcome_verify', email, requested_lang(),
                        os.getenv('BASE_URL') + '/auth/verify?username='******'username']) + '&token=' +
                        urllib.parse.quote_plus(hashed_token))

        username = user['username']

        updates = {}
        for field in [
                'country', 'birth_year', 'gender', 'prog_experience',
                'experience_languages'
        ]:
            if field in body:
                if field == 'experience_languages' and len(body[field]) == 0:
                    updates[field] = None
                else:
                    updates[field] = body[field]

        if updates:
            DATABASE.update_user(username, updates)

        return jsonify(resp)