Exemplo n.º 1
0
def adduser():
    if request.method == "GET":
        return render_template("adduser.html")


#前端post请求,逻辑端通过request.form获取整个表单的值
    if request.method == "POST":
        name = request.form['username']
        name_cn = request.form['username_cn']
        passwd = request.form['password']
        repasswd = request.form['re_password']
        email = request.form['email']
        mobile = request.form['mobile']
        role = request.form['role']
        status = request.form['status']
        userlist = get_userlist(["name"])
        print userlist
        if len(name) == 0 or len(name_cn) == 0 or len(passwd) == 0 or len(
                email) == 0 or len(mobile) == 0:
            content = "这个值不能为空"
            return render_template("adduser.html", content=content)

        if name in map(lambda x: x["name"], userlist):
            content = u"用户已存在"
            return render_template("adduser.html", content=content)
        if passwd != repasswd:
            content = u"您输入的两次密码不一致,请重新输入!"
            return render_template("adduser.html", content=content)
        userinfo = [name, name_cn, passwd, email, mobile, role, status]
        add_user(userinfo)
        return redirect("/")
def adduser():
	if request.method =="GET":
		return render_template("adduser.html")
#前端post请求,逻辑端通过request.form获取整个表单的值
	if request.method =="POST":
		name=request.form['username']
		name_cn=request.form['username_cn']
		passwd=request.form['password']
		repasswd=request.form['re_password']
		email=request.form['email']
		mobile=request.form['mobile']
		role=request.form['role']
		status=request.form['status']
		userlist=get_userlist(["name"])
		print userlist
		if len(name)==0 or len(name_cn)==0 or len(passwd) == 0 or len(email) == 0 or len(mobile) == 0:
			content="这个值不能为空"
			return render_template("adduser.html",content=content)

		if name in map(lambda x:x["name"],userlist):
			content=u"用户已存在"
			return render_template("adduser.html",content=content)
		if passwd !=repasswd:
			content=u"您输入的两次密码不一致,请重新输入!"
			return render_template("adduser.html",content=content)
		userinfo=[name,name_cn,passwd,email,mobile,role,status]
		add_user(userinfo)	
		return redirect("/")
def register():
    if request.method == 'POST':
        login = request.form['login']
        password = request.form['password']
        email = request.form['email']
        fname = request.form['fname']
        sname = request.form['sname']
        phone = request.form['phone']
        address = request.form['address']
        town = request.form['town']
        code = request.form['code']
        country = request.form['country']
        user = {
            'address': address,
            'code': code,
            'country': country,
            'email': email,
            'fname': fname,
            'login': login,
            'password': password,
            'phone': phone,
            'sname': sname,
            'town': town
        }
        users.add_user(user)
        session['logged_in'] = True
        session['user'] = login
        return redirect('/')
    else:
        return render_template('register.html')
Exemplo n.º 4
0
def parse_cmd(cmd):
    print("cmd: {}".format(cmd))
    if cmd[0] == "add user":
        users.add_user()
    elif cmd[0] == "show_all":
        try:
            users.list_employe(cmd[1], cmd[2])
        except IndexError:
            try:
                users.list_employe(cmd[1], False)
            except IndexError:
                users.list_employe("code", False)

    elif cmd[0] == "del_all":
        users.delete_all_employe()

    elif cmd[0] == "find":
        try:
            users.find_user(cmd[1], cmd[2].capitalize())
        except IndexError:
            print(UI_String.COMMAND_NOT_VALIDE.format(2))

    elif cmd[0] == 'x':
        exit(0)
    else:
        print(UI_String.CMD_NOT_AVAILABLE)
Exemplo n.º 5
0
def create_user(username, password, include_apps=None, email_address=None, origin=None):
    if not username:
        raise Exception('Username required')

    if not username.isalnum():
        raise Exception('Username must be alphanumeric')

    if len(username) > 32 or len(username) < 4:
        raise Exception('Invalid username length. Must be between 4 and 32 chars')

    if not password:
        raise Exception('Password required')

    if 8 > len(password) > 64:
        raise Exception('Invalid password length. Must be between 8 and 64 chars')

    if email_address:
        from validate_email import validate_email
        if not validate_email(email_address):
            raise Exception('Email address is malformed')

    if origin and not origin.isalnum():
        raise Exception('Invalid origin field')

    import_json = None
    if origin == 'Happiness':
        import_json = ('UserRoot', True, '/opt/benome/struct/Happiness.json')

    from users import add_user, set_user_config
    from init_db import init_db

    try:
        os.mkdir('/opt/benome/data/{0}'.format(username))
        db_path = '/opt/benome/data/{0}/sql.db'.format(username)
        init_db(db_path, include_apps=include_apps, import_json=import_json)
    except Exception as e:
        # TODO: Remove the data dir
        print e
        raise Exception('Error initializing data')
    else:
        try:
            add_user(username, password)
            set_user_config(username, 'ContainerType', 'Local')
            port = get_next_port()
            set_user_config(username, 'LocalPort', str(port))

            if email_address:
                set_user_config(username, 'EmailAddress', email_address)

            if origin:
                set_user_config(username, 'Origin', origin)

            write_container_conf(username)
            shell('supervisorctl update')
        except Exception as e:
            print e
            raise Exception('Error initializing user.')

    return True
Exemplo n.º 6
0
def status(user):
    '''
    Ensures that the user table has an user, the status table is empty,
    and returns a sample status
    '''
    user_status.table.delete()
    users.add_user(*user)
    return ('status01', user[0], 'This is text')
Exemplo n.º 7
0
 def test_get_users(self):
     users.add_user('kevin', 1, 'password')
     users.add_user('Mike', 2, 'password')
     userlist = users.get_users()
     self.assertEquals(len(userlist), 2)
     unames = ['kevin', 'Mike']
     for u in userlist:
         self.assertIn(u.uname, unames)
Exemplo n.º 8
0
def user_adder(message) -> None:
    telegram_id = message.from_user.id
    user = users.User(telegram_id=telegram_id,
                      group='?',
                      notify=False,
                      friendly=False,
                      last_active=time.time())
    users.add_user(user)
Exemplo n.º 9
0
def process_code(request):
	code, lastfm_user = [request.GET.get(x, '') for x in 'code', 'lastfm_user']
	f = urllib.urlopen('https://oauth.vkontakte.ru/access_token?client_id=%s&client_secret=%s&code=%s' % (secret.VK_CLIENT_ID, secret.VK_CLIENT_SECRET, code))
	resp = f.read()
	res = json.loads(resp)
	access_token = res['access_token']
	user_id = res['user_id']
	users.add_user(vk_id=user_id, access_token=access_token, lastfm_user=lastfm_user)
	return redirect('http://lastfm.initab.ru/vkstatus/?alert=vkstatus_add_ok')
Exemplo n.º 10
0
def test_delete_user(user):
    '''
    Test each aspect of delete_user
    '''
    # Refuse to delete non existant users
    assert not users.delete_user(user[0])
    users.add_user(*user)
    # Sucessfully delete a user
    assert users.delete_user(user[0])
Exemplo n.º 11
0
def status(user):
    '''
    Ensures that the user table has an user, the status table is empty,
    and returns a sample status
    '''
    with sql.connection(sql.STATUS) as table:
        table.delete()
    users.add_user(*user)
    return ('status01', user[0], 'This is text')
Exemplo n.º 12
0
 def test_add_user(self):
     users.add_user('kevin', 1, 'password')
     ret = db.select('Users', where="uname='kevin'")
     user = ret[0]
     self.assertEquals(user.uname, 'kevin')
     self.assertEquals(user.role, 1)
     phash = str(user.password);
     expected = bcrypt.hashpw('password', phash)
     self.assertEquals(expected, phash)
Exemplo n.º 13
0
def new_user():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        users.add_user(username, request.form['password'],
                       request.form['directory'])
        flash('Created user %s.' % username)
        return redirect(url_for('.list_users'))
    return render_template('new_user.html', title='New User', error=error)
Exemplo n.º 14
0
def send_welcome(message):
    check = trafficController.check_spam(message.chat.id)
    if check == "OK":
        bot.send_message(message.chat.id,
                         MSGs.greetings,
                         reply_markup=MSGs.enter_userpass_markup,
                         parse_mode='HTML')
        users.add_user(message)
        trafficController.drop_check(message.chat.id)
Exemplo n.º 15
0
def register_user():
    username_info = username.get()
    password_info = password.get()
    global reg_user_id
    u.add_user(username_info, password_info)
    reg_user_id = u.get_user_id(username_info)
    username_entry.delete(0, END)
    password_entry.delete(0, END)

    Label(register_screen, text="Registration Success", fg="green", font=11).pack()
Exemplo n.º 16
0
def new_user():
    error = None
    if request.method == 'POST':
        username = request.form['username']
        users.add_user(username,
                       request.form['password'],
                       request.form['directory'])
        flash('Created user %s.' % username)
        return redirect(url_for('.list_users'))
    return render_template('new_user.html', title='New User', error=error)
Exemplo n.º 17
0
def pic(user):
    '''
    Ensures that the user table has an user, the picture table is empty,
    the users image directory is deleted, and returns a sample picture
    '''
    with sql.connection(sql.PICTURE) as table:
        table.delete()
    clear_dir(Path(user[0]))
    users.add_user(*user)
    return (user[0], '#car #bmw #sTronG_EMOtiON')
Exemplo n.º 18
0
 def test_delete_user(self):
     users.add_user('kevin', 1, 'password')
     with self.winput as webdata:
         self.input_mock.action ='delete'
         webdata.return_value = self.input_mock
         with self.config:
             with self.assertRaises(Exception):
                 self.manager.POST()
     ret = db.select('Users', where="uname='kevin'")
     with self.assertRaises(IndexError):
         user = ret[0]
Exemplo n.º 19
0
def send_welcome(message):
    check = trafficController.check_spam(message.chat.id, 'start')
    if check == "OK":
        bot.send_message(message.chat.id,
                         MSGs.greetings,
                         reply_markup=MSGs.enter_userpass_markup,
                         parse_mode='HTML')
        users.add_user(message.chat.id)
        print dataBase.check_the_user_in_DB(message)
        users.clear_PLCs(message.chat.id)
        trafficController.finished_process(message.chat.id, 'start')
Exemplo n.º 20
0
 def POST(self):
     if (web.config._session.roleid != 1):
         raise web.seeother('/')
     pdata = web.input(uname=None, action=None)
     if pdata.action == "create":
         users.add_user(pdata.uname, pdata.utype, pdata.pword)
     elif pdata.action == "modify":
         users.modify_user(pdata.uname, pdata.utype)
     elif pdata.action == 'delete':
         users.del_user(pdata.uname)
     raise web.seeother('/manager')
Exemplo n.º 21
0
def test_modify_user(user):
    '''
    Test each aspect of modify_user
    '''
    # Refuse to modify non existant users
    assert not users.modify_user(*user)
    users.add_user(*user)
    # Sucessfully modify a user
    assert users.modify_user(*user)
    # Refuse users breaking requirements
    assert not users.modify_user(*user[:2], '*' * 31, user[3])
    assert not users.modify_user(*user[:3], '*' * 101)
Exemplo n.º 22
0
def test_add_user(user):
    '''
    Test each aspect of add_user
    '''
    # Sucessfully add an user
    assert users.add_user(*user)
    # Refuse duplicate users
    assert not users.add_user(*user)
    # Refuse users breaking requirements
    assert not users.add_user('*' * 31, *user[1:])
    assert not users.add_user(*user[:2], '*' * 31, user[3])
    assert not users.add_user(*user[:3], '*' * 101)
Exemplo n.º 23
0
def test_search_user(user):
    '''
    Test each aspect of search_user
    '''
    # Return empty dictionary for non existant users
    data = users.search_user(user[0])
    assert data['user_id'] is None
    users.add_user(*user)
    # Sucessfully find a user
    data = users.search_user(user[0])
    assert data['user_id'] == user[0]
    assert data['user_email'] == user[1]
    assert data['user_name'] == user[2]
    assert data['user_last_name'] == user[3]
Exemplo n.º 24
0
def registerSubmit():
    """
    注册用户填写完毕后提交请求
    :return:
    """
    flowTowDataBase = COMP249Db()
    userNick = users.session_user(db=flowTowDataBase)
    if userNick:
        registerInfo = "Please logout first"
        showRegister = False
    else:
        nick = request.POST.get("nick")
        password = request.POST.get("password")
        if users.add_user(flowTowDataBase, nick, password):
            registerInfo = "Registered successfully!You can login in the upper right corner now."
            showRegister = False
        else:
            registerInfo = "Registration failed, your registered user name already exists."
            showRegister = True
    renderDict = {
        "title": "FlowTow!",
        "homeActive": False,
        "aboutActive": False,
        "userNick": userNick,
        "myActive": False,
        "registerInfo": registerInfo,
        "showRegister": showRegister
    }
    return template("register", renderDict)
Exemplo n.º 25
0
def get_time(message):
    global wait_for_time

    if (wait_for_time == True and is_time(message)):
        time = process_time(message)
        add_user(message.chat.id, time[0], time[1])
        wait_for_time = False
        bot.send_message(
            message.chat.id, "Отлично, установлено время сообщений: " +
            str(time[0]) + ":" + str(time[1]) + "." +
            "\r\nНа данный момент актуальная информация: ")
        bot.send_message(message.chat.id,
                         get_information(),
                         parse_mode="Markdown")
    else:
        bot.send_message(message.chat.id, "Не понимаю :с")
Exemplo n.º 26
0
Arquivo: app.py Projeto: Zabari/kollel
def login():
    admin = False
    google_dictionary = request.get_json()
    id_token = google_dictionary["tokenId"]
    url = f"https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={id_token}"
    google_request = requests.post(url)
    authorized_dictionary = google_request.json()
    user_id = False
    if (
        (google_request.status_code == 200) and
        (secret_keys["google_client_id"] == authorized_dictionary["aud"])
    ):
        user_id = users.exists(authorized_dictionary)
        if (not user_id):
            user_id = users.add_user(authorized_dictionary)
        else:
            admin = user_id["admin"]
            user_id = user_id["id"]
        if (admin):
            session["admin"] = admin
        session["id"] = user_id
        session["survey"] = users.is_survey_done(session["id"])
    return jsonify({
                        "id": "id" in session,
                        "admin": admin,
                        "survey": "survey" in session and session["survey"]
                    })
Exemplo n.º 27
0
def test_delete_status(db):
    assert users.add_user(
        ("test1", "*****@*****.**", "tester", "one"), db) is True
    assert user_status.add_status(
        ["test1_status_id", "test1", "test status text"], db) is True
    assert user_status.delete_status("test1_status_id", db) is True
    assert user_status.delete_status("test1_status_id", db) is False
    assert user_status.delete_status("other_status_id", db) is False
Exemplo n.º 28
0
def register():
    #Get Registration Form
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        #Get Register form fields
        name = form.name.data
        email = form.email.data
        username = form.username.data
        password = sha256_crypt.encrypt(str(form.password.data))

        add_user(name=name, email=email, username=username, password=password)

        flash('You are now registered, can log in', 'success')

        return redirect(url_for('index'))

    return render_template('register.html', form=form)
Exemplo n.º 29
0
def add_user(user_id, email, user_name, user_last_name, db):
    '''
    Requirements:
    - user_id cannot already exist in db
    - Returns False if there are any errors
    - Otherwise, it returns True.
    '''
    return users.add_user([user_id, email, user_name, user_last_name], db)
Exemplo n.º 30
0
def add_user_endpoint():
    content = request.form
    if not content:
        return "<h1> Error! </h1><p>You need some form content</p>"
    username, password = content.get("username"), content.get("password")
    email, fullname = content.get("email"), content.get("name")
    user_from_db = find_user(username)
    if user_from_db:
        return "<h1> Error! </h1> Your username already has an account!"
    return add_user(username, password, email, fullname)
Exemplo n.º 31
0
def test_add_status(db):
    assert users.add_user(
        ("test1", "*****@*****.**", "tester", "one"), db) is True
    assert user_status.add_status(
        ["test1_status_id", "test1", "test status text"], db) is True
    assert user_status.add_status(
        ["test1_status_id", "test1", "test status text"], db) is False
    assert user_status.add_status(
        ["test1_status_id", "Non_existant_user_id", "test status text"],
        db) is False
def test_delete_user(db):
    assert users.add_user(
        ("test1", "*****@*****.**", "tester", "one"), db) is True
    assert users.add_user(
        ("test2", "*****@*****.**", "tester", "two"), db) is True

    assert user_status.add_status(
        ["test1_status_id", "test1", "test status text"], db) is True

    assert users.delete_user("test1", db) is True
    assert list(db['users']) == [{
        'id': 2,
        'NAME': 'tester',
        'EMAIL': '*****@*****.**',
        'USER_ID': 'test2',
        'LASTNAME': 'two'
    }]

    assert user_status.search_status("test1_status_id", db) is None
Exemplo n.º 33
0
def root():
    if request.method == 'POST':
        button = request.form['button']
        if button  == 'join':
            if request.form['password'] == request.form['password_confirmation']:
                if users.get_uuid(userdb, request.form['email']) is not None:
                    
                    msg = (gettext("An account already exists for that email address. Please either use another email address or use the recover password feature."))
                    app.logger.warn("Account already exists for "+str(request.form['email']))
                else:

                    lang = request.accept_languages.best_match(LANGUAGES.keys())

                    uuid = users.add_user(userdb, request.form['email'], request.form['password'], request.form['first_name'], request.form['last_name'], lang)
                
                    subject = gettext("SUPERHUB Project :: New Journey Diary Account")
                    content = gettext("A new SUPERHUB Journey Diary account has been created for the following email address: {kwarg}. You should now be able to log into the journey diary and record your journeys.").format(kwarg=request.form['email'])

                    # Added a toggle for the email confirmation service, as it was causing problems on my server. You can re-enable it in the config.
                    if (app.config['send_mail'] == "True"):
                        mail.send(app.config['email_address'], app.config['email_password'], request.form['email'], subject, content)
                        msg = gettext("An email has been sent to {kwarg} so that you can verify your email address. However you can log into your account immediately.").format(kwarg=request.form['email'])
                    else:
                        msg = gettext("A confirmation email could not be sent at this time. You can still sign in to your account right away")
                        app.logger.warn("Confirmation email was not sent to " +str(request.form['email'])+" as outgoing mail is disabled. See config.")
                    
                    logline = { 'type':'New user reqistration', 'timestamp': str(datetime.now().isoformat()), 'data': {'email': request.form['email'], 'uuid':uuid}, 'payload': None}                    
                    app.logger.info( json.dumps(logline) )
            else:
                msg = gettext("The supplied passwords do not match. Please ensure that you type the same password into both the password box and the confirmation box.")

            flash(msg)
           
        elif button == 'login':
            if check_auth(request.form['email'], request.form['password']):
                session['email'] = request.form['email']
                session['uuid'] = users.get_uuid(userdb, session['email'])
                session['logged_in'] = True
                return redirect(request.args['next'] if 'next' in request.args else url_for('.dashboard'))
            
            msg = gettext("The supplied password was incorrect")
            flash(msg)
            return render_template('index.html')

    try:
        if session['cookie_notified']:
            return render_template('index.html')
    except KeyError:
        alertlist = [
            {
                "msg":gettext('This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies.'),
                "type":"cookie_notification",
            }
        ]
        return render_template('index.html', alertlist = alertlist)
Exemplo n.º 34
0
def test_modify_status(db):
    assert users.add_user(
        ("test1", "*****@*****.**", "tester", "one"), db) is True
    assert user_status.add_status(
        ["test1_status_id", "test1", "test status text"], db) is True
    assert user_status.modify_status("test1_status_id", "test1",
                                     "new status text", db) is True
    assert user_status.modify_status("status_id_not_in_db", "test1",
                                     "some status", db) is False
    assert user_status.modify_status("status_id_not_in_db", "baduserid",
                                     "some status", db) is False
def test_search_user(db):
    assert users.add_user(
        ("test1", "*****@*****.**", "tester", "one"), db) is True
    assert users.search_user("test1", db) == {
        'id': 1,
        'NAME': 'tester',
        'EMAIL': '*****@*****.**',
        'USER_ID': 'test1',
        'LASTNAME': 'one'
    }
    assert users.search_user("test2", db) is None
Exemplo n.º 36
0
def login_success(token, profile):
    if profile:

        domain = profile['email'].split('@')[1]
        if domain in config.ALLOWED_DOMAINS or profile['email'] in config.WHITELIST:
            add_user(profile)
            session['is_admin'] = False
            session['user'] = profile
            
            if profile['email'] in config.ADMINS:
                session['is_admin'] = True
            return redirect(url_for('bp.tag', q='tag'))

        else:
            flash('Invalid credentials', 'error')
            return redirect(url_for('bp.login'))

    else:
        print('Login failed.')
        return "Login failed"
Exemplo n.º 37
0
def add_user(user_id, email, user_name, user_last_name):
    '''
    Creates a new instance of User and stores it in the database

    Requirements:
    - user_id cannot already exist in the database
    - Returns False if there are any errors
    - Otherwise, it returns True.
    '''
    logger.info('Adding a new User')
    return users.add_user(user_id, email, user_name, user_last_name)
Exemplo n.º 38
0
def register():
  username = request.forms.get("username")
  password = request.forms.get("password")
  password2 = request.forms.get("password2")
  data = {"username":username, 
          "messages":[],
          "warnings": []} 
  
  if password == password2 and username:
    try:
      users.add_user(username, password)
    except UserNameExistsException as ex:
      data["warnings"].append("This username is already taken")
      return renderfile("register", data)
    return login()
  elif not username:
    data["warnings"].append( "You can't have an empty name")
  elif password != password2:
    data["warnings"].append( "Your two passwords don't match")
  return renderfile("register", data)
Exemplo n.º 39
0
def test_search_status(db):
    assert users.add_user(
        ("test1", "*****@*****.**", "tester", "one"), db) is True
    assert user_status.add_status(["test1_status_id", "test1", "test me"],
                                  db) is True
    assert user_status.search_status("test1_status_id", db) == {
        'id': 1,
        'STATUS_ID': 'test1_status_id',
        'USER_ID': 'test1',
        'STATUS_TEXT': 'test me'
    }
    assert user_status.search_status("another_status_id", db) is None
Exemplo n.º 40
0
def addUser():
    if request.method == 'GET':
        return render_template('add_user.html')
    elif request.method == 'POST':
        name = request.form.get('name')
        password1 = request.form.get('passwd1')
        password2 = request.form.get('passwd2')
        age = request.form.get('age')
        job = request.form.get('job')
        if vilidata_isUser(name):
            # return render_template('add_user.html',error=u'用户已存在!')
            print vilidata_isUser(name)
            return render_template('add_user.html', error=u'用户名存在,请重新输入')
        elif not check_user_input(
                username=name, password1=password1, password2=password2):
            return render_template('add_user.html', error=u'用户名、密码是必填项!')
        elif not check_user_password(passwd1=password1, passwd2=password2):
            return render_template('add_user.html', error=u'两次输入的密码不一致!')
        else:
            add_user(name=name, passwd=password1, job=job, age=age)
            return render_template('add_user.html', error=u'注册成功!')
Exemplo n.º 41
0
def root():
    if request.method == 'POST':
        button = request.form['button']
        if button  == 'join':
            if request.form['password'] == request.form['password_confirmation']:
                if users.get_uuid(userdb, request.form['email']) is not None:
                    
                    msg = (gettext("An account already exists for that email address. Please either use another email address or use the recover password feature."))
                    app.logger.warn("Account already exists for "+str(request.form['email']))
                else:

                    lang = request.accept_languages.best_match(LANGUAGES.keys())

                    uuid = users.add_user(userdb, request.form['email'], request.form['password'], request.form['first_name'], request.form['last_name'], lang)
                
                    subject = gettext("SUPERHUB Project :: New Journey Diary Account")
                    content = gettext("A new SUPERHUB Journey Diary account has been created for the following email address: {kwarg}. You should now be able to log into the journey diary and record your journeys.").format(kwarg=request.form['email'])

                    mail.send(app.config['email_address'], app.config['email_password'], request.form['email'], subject, content)

                    msg = gettext("An email has been sent to {kwarg} so that you can verify your email address. However you can log into your account immediately.").format(kwarg=request.form['email'])
                    
                    logline = { 'type':'New user reqistration', 'timestamp': str(datetime.now().isoformat()), 'data': {'email': request.form['email'], 'uuid':uuid}, 'payload': None}                    
                    app.logger.info( json.dumps(logline) )
            else:
                msg = gettext("The supplied passwords do not match. Please ensure that you type the same password into both the password box and the confirmation box.")

            flash(msg)
           
        elif button == 'login':
            if check_auth(request.form['email'], request.form['password']):
                session['email'] = request.form['email']
                session['uuid'] = users.get_uuid(userdb, session['email'])
                session['logged_in'] = True
                return redirect(request.args['next'] if 'next' in request.args else url_for('.dashboard'))
            
            msg = gettext("The supplied password was incorrect")
            flash(msg)
            return render_template('index.html')

    try:
        if session['cookie_notified']:
            return render_template('index.html')
    except KeyError:
        alertlist = [
            {
                "msg":gettext('This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies.'),
                "type":"cookie_notification",
            }
        ]
        return render_template('index.html', alertlist = alertlist)
Exemplo n.º 42
0
def register():
    """Registers the user."""
    # if g.user:
        # return redirect(url_for('timeline'))
    error = None
    if request.method == 'POST':
        if not request.form['username']:
            error = 'You have to enter a username'
        elif not request.form['email'] or \
                '@' not in request.form['email']:
            error = 'You have to enter a valid email address'
        elif not request.form['password']:
            error = 'You have to enter a password'
        elif request.form['password'] != request.form['password2']:
            error = 'The two passwords do not match'
        elif get_user('username', request.form['username']) is not None:
            error = 'The username is already taken'
        else:
            add_user(request.form['username'], request.form[
                     'password'], request.form['email'])
            flash(
                'You were successfully registered and can login now', 'success')
            return redirect(url_for('login'))
    return render_template('register.j2', error=error)
Exemplo n.º 43
0
def register():
	for i in range(0, len(bots)):
		users.add_user(str(i))
Exemplo n.º 44
0
Arquivo: app.py Projeto: xymostech/til
def register():
    if users.add_user(request.form['username'], request.form['password']):
        return redirect(url_for('login'))
    else:
        return render_template("login.html",
                               register_error="Couldn't register that username")
Exemplo n.º 45
0
          "7. Display house listings\n"
          "8. Sign off.\n")
    
    number = raw_input('Enter your option: ')
    
    try:
        choice = int(number)
        
        if choice == 1:
            name = raw_input('What is your name?\n')           #passed from webpage
            gender = raw_input('What is your gender?\n')       #passed from webpage
            age = raw_input('What is your age?\n')             #passed from webpage
            email = raw_input('What is your email?\n')         #passed from webpage
            password = raw_input('What is your password?\n')   #passed from webpage

            users.add_user(name, gender, age, email, password)

        elif choice == 2:
            email = raw_input('What is your email?\n')         #passed from webpage
            password = raw_input('What is your password?\n')   #passed from webpage
        
            users.login(email, password)

        elif choice == 6:
            name = raw_input('What is the listing name?\n')           #passed from webpage
            addr = raw_input('What is the address?\n')       #passed from webpage
            desc = raw_input('Short description?\n')             #passed from webpage
            price = raw_input('What is the monthly price?\n')         #passed from webpage
        
            house_listings.add_house(name, addr, desc, price)