コード例 #1
0
def register(is_super):
    '''returns login() which returns (is_super,username) and asks for a unique username and
    a password with at least one upper case, one lower case, one number, one of
    @#$ and at least 8 characters long as separate inputs then adds username,
    password and initial_money to corresponding table determined by is_super'''
    while 1:
        username = viewer.ask_register_username()
        if len(findall(r"\s", username)) != 0:
            viewer.error_username_spaces()
        elif model.check_username(username):
            viewer.error_username_taken()
        else:
            break

    while 1:
        password = viewer.ask_register_password()
        if len(
                findall(r"(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@#$]).{8,}",
                        password)) > 0 and len(findall(r"\s", password)) == 0:
            break
        viewer.error_password()

    model.add_user(username, password, initial_money, is_super)
    viewer.done_register(is_super, username)
    return login()
コード例 #2
0
def crawl(output, startUser='******'):

    queue = Queue()
    queue.put(startUser)

    count = 0
    while count < 100 and not queue.empty():
        username = queue.get()
        print('[{}] {}'.format(count, username))
        followings = get_following(username)
        for following in followings:
            queue.put(following)

        count += 1

        if model.exists_user(username):
            continue

        info = get_information(username)
        fullname = info['fullname']
        location = info['location']
        if location is None:
            continue

        print('username: {}, fullname: {}, location: {}'.format(username, fullname, location))
        model.add_user(username, fullname, location)
コード例 #3
0
ファイル: view.py プロジェクト: pcote/LearningMachine
def login():
    """
    Log in the user to the system using Google oauth login.
    Note: What gets done here depends on what phase of the login process we are in.
    If this is the INITIAL PHASE, then send the user to the Google login.
    If we are COMING BACK from a Google login, use the code to get the email and display name set up for the user.
    :return: An appropriate redirect (depending on what step of the login process this is.
    """
    domain = parser["learningmachine"]["domain"]
    secrets_file = "{}/{}".format(dir_path, "client_secret.json")
    scope = "https://www.googleapis.com/auth/userinfo.email"
    redirect_uri = "http://{}/login".format(domain)
    login_handler = LoginHandler(secrets_file, scope, redirect_uri)

    if "code" in request.args:
        login_handler.setup_user_info(request.args["code"])
        session["email"] = login_handler.email
        session["display_name"] = login_handler.display_name

        if not model.user_exists(login_handler.email):
            msg = "Adding user: {} with ID of {} to the database."\
                .format(login_handler.email, login_handler.display_name)
            model.add_user(login_handler.email, login_handler.display_name)

        msg = "Sending user: {} to main page".format(login_handler.email)
        app.logger.info(msg)
        return redirect("/static/main.html")

    else:
        msg = "No login code yet.  Letting Google handle the login process at: {}"\
                .format(login_handler.auth_url)
        app.logger.info(msg)
        return redirect(login_handler.auth_url)
コード例 #4
0
def register():
    if request.method == 'POST':
        user_username = request.form['username']
        user_email = request.form['user-email']
        user_pass = request.form['user-password']
        repeat_pass = request.form['repeat-password']

        users = model.get_users()
        error = None
        for user in users:
            if user_username == user[1] and user_email == user[2]:
                error = 'The username and email is already taken'
            if user_username == user[1]:
                error = 'The username is already taken'
            if user_email == user[2]:
                error = 'The email is already taken'
            if error:
                flash(error)
                return render_template('register.html')

        query = '''INSERT INTO users(username, email, password, joined_at, is_admin)
                   VALUES(%s, %s, %s, %s, %s)'''
        values = (user_username, user_email, user_pass, datetime.now(), False)

        model.add_user(query, values)
        flash('Registered Successfuly!')
        return redirect(url_for('index'))

    return render_template('register.html')
コード例 #5
0
ファイル: utils.py プロジェクト: jkeillor/jkeillor.com
def make_user(username, password):
    existing = model.get_user(username)
    if existing:
        print "Updating existing user"
        model.update_user(username, password)
    else:
        print "Creating new user"
        model.add_user(username, password)
コード例 #6
0
ファイル: app.py プロジェクト: madpark13/Flask-PKS21
def index():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']
        password_check = request.form['password_check']
        add_user(name, email, password)
        return redirect('/users/' + name)
    return render_template('index.html')
コード例 #7
0
def process_signup():
    email = request.form['username']
    password = request.form['password']
    age = request.form['age']
    gender = request.form['gender']
    occupation = request.form['occupation']
    zipcode = request.form['zipcode']
    model.add_user(email, password, age, gender, occupation, zipcode)
    return redirect("/")
コード例 #8
0
def register():
	error = None
	if request.method == 'POST':
		if model.check_user(escape(request.form['username'])):
			error = 'Username already exists'
		else:
			session['username'] = request.form['username']
			model.add_user(escape(request.form['username']), request.form['password'])
			flash('You were registered')
			return redirect(url_for('index'))
	return render_template('register.html', error=error, registering=True)
コード例 #9
0
ファイル: code_backup.py プロジェクト: Tangdongle/CHESS
 def POST(self):
     i = web.input()
     user_form = self.form()
     if not user_form.validates():
         return render.admin(model.get_all_users(),user_form)
     if 'uid' in i:
         model.del_user(i.cin, i.uid)
     elif 'username' in i:
         uname, pwd, email = i.username.strip().lower(), i.password.strip(), i.email.strip()
         pwd = bcrypt.hashpw(pwd, bcrypt.gensalt(BCRYPT_WLOAD))
         model.add_user(i.cin, uname,pwd, email)
     return render.admin(model.get_all_users(), user_form)
コード例 #10
0
def registration():
    form = Register(request.form)
    if request.method == 'POST':
        if form.validate() == True:
            global username
            username = request.form['username']
            password = request.form['password']
            model.add_user(username,password)
            return redirect(url_for('show_account'))
        else:
            return render_template('registration.html', form=form)
    elif request.method == 'GET':
        return render_template('registration.html', form=form)
コード例 #11
0
ファイル: app.py プロジェクト: smialy/ssrp
def registration():
    if request.method == 'POST':
        login = request.form['login']
        salt = request.form['salt']
        v = request.form['v']
        
        if model.has_user(login):
            return jsonify(dict(error=True, message="User exits"))
        
        model.add_user(login, salt, v)
        return jsonify(dict(error=False))
    else:
        return render_template('registration.html')
コード例 #12
0
ファイル: code_backup.py プロジェクト: Tangdongle/CHESS
 def POST(self):
     i = web.input()
     form = self.form()
     if not form.validates() or i.username in [u.username for u in model.get_all_users()]:
         return render.register(form,model.get_all_users())
     else:
         cin, uname, pwd, email = i.cin, i.username.strip().lower(), i.password.strip(), i.email.strip()
         #register parsing here
         pwd = bcrypt.hashpw(pwd, bcrypt.gensalt(BCRYPT_WLOAD))
         model.add_user(cin, uname,pwd, email)
         session.logged_in = True
         session.username = uname
         session.cin = cin
         raise web.seeother('/')
コード例 #13
0
ファイル: telegram_beer.py プロジェクト: nip3o/beer
def command_register(update):
    parts = update.message.text.split()

    if not len(parts) == 3:
        raise InvalidCommand('Usage: /register username password')

    username, password = parts[1:]
    try:
        BeerBot(username, password).get_weblaunch_start()
    except LoginException:
        return {'text': 'Invalid username or password.'}

    model.add_user(update.message.chat_id, username, password)
    return {'text': 'Created user.'}
コード例 #14
0
ファイル: app.py プロジェクト: BennySpaceman/firstWEB
def index():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']
        password_check = request.form['password_check']
        if password != password_check:
            return render_template('index.html', error='passwords_dont_match')
        try:
            add_user(name, email, password)
        except AccountExists:
            return render_template('index.html', error='account_already_exists')
        session['account'] = name
        return redirect('/users/' + name)
    return render_template('index.html')
コード例 #15
0
def new_user(user_name, password, first, last, email):
    try:
        add = model.add_user(user_name, password, first, last, email)
        return add
    except Exception as e:
        print('add new user error ', e)
        return e
コード例 #16
0
ファイル: Response.py プロジェクト: bjornlevi/CoBlog
def shuotest1():  
    results = ''
    results += '<p>[TEST] ADD a user, list the number of users, and all users name and email</p>'
    name = 'Lucy'
    pwd = 'llll'
    email = name +'@brandeis.edu' 
    
    #test
    #model.add_user(name,pwd,email)
    
    #for count in  model.add_user('Alex','1','*****@*****.**'):
        #results += '<p>add a new user</p><br/><p>current total number of users: ' + str(count['total_user']) + '</p><hr/>'

    #results +='<p>TOTAL USERS: '+str(model.add_user('Kiki','000','*****@*****.**'))+'</p>'
    #test
    for total in DB().query('SELECT COUNT(*) AS total_user FROM users'):
        results +='<p>total users:'+str(total['total_user'])+'</p>'
        
    #test, add a user
    results +='<p>[TEST] Add a user:'******'</p>'
    
    
    for row in model.get_users():
        results += '<p>'+row['user']+' '+ row ['email']+'</p>'
    
    return results
コード例 #17
0
def post_signup():
    # Handle the form processing
    username = request.forms.get('username')
    password = request.forms.get('password')

    # Call the appropriate method
    return model.add_user(username, password)
コード例 #18
0
def add_post():
    session_user_email = session['username']

    query = 'SELECT * from users WHERE email = %s'
    values = (session_user_email, )
    user = model.get_users(query, values)

    if request.method == 'POST':
        value_post = request.form['new-post']
        query = 'INSERT INTO posts(value, user_id) VALUES(%s, %s)'
        values = (value_post, user[0][0])
        model.add_user(query, values)

        posts = get_posts()

    return render_template('index.html', posts=posts)
コード例 #19
0
ファイル: code.py プロジェクト: Tangdongle/CHESS
 def POST(self):
     if not check_priv_lvl(2):
         raise web.notfound("You don't have the right privilege level to access this")
     i = web.input(cin=None)
     user_form = self.form()
     client_form = self.cin_form()
     if 'uid' in i:
         logger.info("Deleting user")
         model.del_user(i.cin, i.uid)
         logger.debug('User Deleted: %d',i.uid)
     elif 'new_client' in i:
         if client_form.validates():
             logger.info("Adding new client")
             model.add_client(i.new_client, i.client_name)
             logger.debug('Client Added: %d|%s',i.new_client, i.client_name)
     elif 'username' in i:
         logger.info("Adding user")
         if not user_form.validates():
             return render.admin(model.get_all_users() if session.cin==0 else model.get_user_by_cin(session.cin), user_form, client_form)
         uname, pwd, email = i.username.strip().lower(), i.password.strip(), i.email.strip()
         pwd = bcrypt.hashpw(pwd, bcrypt.gensalt(BCRYPT_WLOAD))
         cin = i.cin if i.cin else session.cin
         ret = model.add_user(cin, uname,pwd, email, i.privilege)
         #Checks if CIN exists and if CIN/Username combination exists
         if ret == 0:
             raise web.notfound("No client exists with this CIN")
         elif ret == -1:
             raise web.notfound("Username exists with identical CIN")
         logger.debug('User added %s', uname)
     raise web.seeother('/admin')
コード例 #20
0
ファイル: app.py プロジェクト: smolgeat/Summer-2020-MWML
def home():
    start = time.time()
    ratings = {}
    movieId = m.title_to_id([
        'Toy Story', 'Toy Story 2', "Toy Story 3", "The Lion King",
        "A Bug's Life", "The Hunchback of Notre Dame"
    ], links)
    for movie in movieId:
        ratings[movie] = 5
    data = m.add_user(ratings, df)
    model = m.train_model(data)
    #get n movie suggestions
    user = df['userId'].max()
    n_movies = 5
    suggestions = np.array(m.make_predictions(user, df, model, n_movies))
    #select the movie id
    suggested_movie_id = suggestions[:, 0]
    #return titles to user
    titles = m.id_to_title(suggested_movie_id, links)
    suggested_titles = {}
    suggested_titles['Suggested Titles'] = titles
    suggested_titles['Watched Titles'] = [
        'Toy Story', 'Toy Story 2', "Toy Story 3", "The Lion King",
        "A Bug's Life", "The Hunchback of Notre Dame"
    ]
    end = time.time()
    minutes = round((end - start) / 60)
    seconds = get_seconds(start, end)
    suggested_titles['minutes'] = minutes
    suggested_titles['seconds'] = seconds
    return suggested_titles
コード例 #21
0
def registration(name, age, phone, addr, email, uname, pword):
    res = model.check_username(uname)
    if (res is None):
        status = model.add_user(name, age, phone, addr, email, uname, pword)
        return status
    else:
        return "Exist"
コード例 #22
0
ファイル: app.py プロジェクト: busterroni/web.py-forum
    def POST(self):
        form=self.registerForm
        if not form.validates():
            return render.register(self.registerForm, "The form did not validate.")
        else:
            username=form.d.username
            password=form.d.password
            email=form.d.email
            users=db.select('users')
            for user in users:
                if username==user.username:
                    return render.register(self.registerForm, "Username already taken")

            hashedPassword=bcrypt.hashpw(password, bcrypt.gensalt())
            model.add_user(username, hashedPassword, email)
            return render.register(self.blankForm, "Success!")
コード例 #23
0
def sign_up():
    email = request.form.get("email")
    password = hash(request.form.get("password"))
    age = request.form.get("age")
    zipcode = request.form.get("zipcode")

    new_user = model.User(email = email, password = password, age = age, zipcode = zipcode)
    user_id = model.add_user(new_user)
    session['user_id'] = user_id
    return redirect(url_for("view_user_ratings", user_id = user_id))
コード例 #24
0
ファイル: Response.py プロジェクト: bjornlevi/CoBlog
def add_user():
    #SHUO: should get name, pwd, and emial from the registration page. 
    #name = 'Jeanne'
    #pwd = '222'
    #email = name +'@brandeis.edu' 
    name = bottle.request.forms.get('user')
    pwd = bottle.request.forms.get('password')
    email = bottle.request.forms.get('email')
    
    results = ''
    results +=model.add_user(name, pwd, email)
    return results
コード例 #25
0
ファイル: judgment.py プロジェクト: rebeccastandig/judgment
def new_user():
    email = request.form.get("email")
    pwd = request.form.get("password")
    verify_pwd = request.form.get("password_verify")
    age = request.form.get("age")
    zipcode = request.form.get("zipcode")

    if (pwd == verify_pwd) and (email and pwd and age and zipcode):
        if model.is_user(email):
            flash("You're already registered. Please sign in.")
            return redirect(url_for("signin"))
        else:
            model.add_user(email, pwd, age, zipcode)
            flash("Thanks for registering! Please sign in.","success")
            return redirect(url_for("signin"))
    elif pwd != verify_pwd:
        flash("Passwords must match.","error")
        return redirect(url_for("register"))
    else:
        flash("All fields are required.","error")
        return redirect(url_for("register"))
コード例 #26
0
ファイル: app.py プロジェクト: hunterSThompson/hangman
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        result = model.add_user(username, password)
        if result:
            user = User.get(username)
            login_user(user)
            return redirect("/")
        else:
            return render_template("register.html", error=True)
    else:
        return render_template('register.html')
コード例 #27
0
def signup():
    if session.get("username"):
        return redirect(url_for("search"))

    if request.method == "POST":
        username = request.form["username"]
        email = request.form["email"]
        password = request.form["password"]
        password = generate_password_hash(password)

        if get_user_by_name(username):
            flash("Пользователь с таким именем уже зарегистрирован!")
            return redirect(url_for("signup"))
        elif get_user_by_email(email):
            flash("Пользователь с такой почтой уже зарегистрирован!")
            return redirect(url_for("signup"))
        else:
            add_user(username, email, password)
            session["username"] = username
        return redirect(url_for("search"))

    return render_template("signup.html")
コード例 #28
0
ファイル: server.py プロジェクト: manishapme/hb_ratings
def register_user():
    """Register or sign up user"""

    #post requests mean they've submitted form on register.html
    if request.method == 'POST':
        user_email = request.form.get('email')
        user_password = request.form.get('password')
        user_age = int(request.form.get('age'))
        user_zipcode = request.form.get('zipcode')
        result = get_user_by_email(user_email) #querying DB for username

        if result:
            ##SHOW ALERT, "username exists"
            flash('That %s already exists. Please login or use a different email' % user_email)
            return redirect('/register')
        else:
            add_user(user_email, user_password, user_age, user_zipcode)
            flash('%s has been successfully registered and logged in.' % user_email)
            session['user_id'] = result.user_id
            return redirect('/')
    else:
        # coming from link on homepage.html
        return render_template("register.html")
コード例 #29
0
ファイル: main.py プロジェクト: rcdelga/Blogz
def signup():
    if request.method == 'POST':
        entries = {
            'username': request.form['username'],
            'password1': request.form['password1'],
            'password2': request.form['password2']
        }
        errors = {
            'username_error': '',
            'password1_error': '',
            'password2_error': ''
        }
        for entry in entries:
            if not 2 < len(entries[entry]) < 21 and ' ' not in entries[entry]:
                errors[
                    entry +
                    '_error'] = "Invalid Entry: Requires 2-20 characters with no spaces."
                if entry == 'username':
                    entries[entry] = ''
        if entries['password1'] != entries['password2']:
            error = "Passwords do not match."
            errors['password1_error'] = error
            errors['password2_error'] = error
        if existing_user(entries['username']):
            errors['username_error'] = "[{0}] is already registered.".format(
                entries['username'])
            entries['username'] = ''
        for entry in errors:
            if errors[entry]:
                entries['password1'] = ''
                entries['password2'] = ''
                return render_template('signup.html', **entries, **errors)
        add_user(entries['username'], entries['password1'])
        session['username'] = entries['username']
        return redirect('/blog')
    return render_template('signup.html')
コード例 #30
0
def signup():
    if request.method == 'GET':
        message = "Please sign up"
        return render_template("signup.html", message=message)
    else:
        username = request.form['username']
        password = request.form['password']
        password_confirm = request.form['password_confirm']
        if password != password_confirm:
            message = "passwords do not match"
            return render_template("signup.html", message=message)
        else:
            insert = model.add_user(username, password)
            message = "Registration successful!"
            return render_template("signup.html", message=insert)
コード例 #31
0
ファイル: controller.py プロジェクト: FihlaTV/hb_dogwalker
def register():
    """Register new user and login."""

    # @todo validate form data in javascript
    user_name = request.form.get('register_user_name')
    password = request.form.get('register_password')
    first_name = request.form.get('register_first_name')
    last_name = request.form.get('register_last_name')
    email = request.form.get('register_email')
    business_name = request.form.get('register_business_name')
    # store password as hash
    password = bcrypt.generate_password_hash(password)

    # ensure username is unique (case insensitive)
    user = User.query.filter(User.user_name.ilike(user_name)).first()

    if user:
        flash(
            'The username {} is already in use. Please select another username.'
            .format(user_name))
        return redirect('/')

    else:
        new_user = add_user(user_name=user_name,
                            password=password,
                            first_name=first_name,
                            last_name=last_name,
                            email=email)
        login_user(new_user)
        # @todo needs to be broken out for future implementation of multiple users
        # @todo needs to check for duplicate businesses
        if business_name:
            # if a business name was entered, create that business and associate with this user
            new_business = add_business(business_name=business_name,
                                        business_street='',
                                        business_city='',
                                        business_state='',
                                        business_zip='',
                                        business_phone='',
                                        url='',
                                        license='')
            new_user.update_user(business_id=new_business.id)
            return redirect('/business/{}'.format(current_user.business_id))
        else:
            return redirect('/business')
コード例 #32
0
def start(bot, update):

    chat_id = update.message.chat_id
    db_management.DBManagementHelper().update_index(chat_id, 0)
    db_management.DBManagement().update_movie(chat_id)
    exist_user = ""
    if not model.add_user(chat_id):
        model.update_status(chat_id, 'start')
        exist_user = "******"

    message = f"Welcome {exist_user} to Go2Movie bot!\n" \
              "Give me an example of a movie you like and I'll find you a movie you'll like."

    logger.info(f"> Start chat #{chat_id}")

    keyboard = [[InlineKeyboardButton("Add movie", callback_data='1')]] if not exist_user else \
        [[InlineKeyboardButton("Add movie", callback_data='1'),
          InlineKeyboardButton("Get recommendations", callback_data='2')]]

    reply_markup = InlineKeyboardMarkup(keyboard)
    bot.send_message(chat_id=chat_id, text=message, reply_markup=reply_markup)
コード例 #33
0
ファイル: controller.py プロジェクト: manishapme/hb_dogwalker
def register():
    """Register new user and login."""
    
    # @todo validate form data in javascript
    user_name = request.form.get('register_user_name')
    password = request.form.get('register_password')
    first_name = request.form.get('register_first_name')
    last_name = request.form.get('register_last_name')
    email = request.form.get('register_email')
    business_name = request.form.get('register_business_name')
    # store password as hash
    password = bcrypt.generate_password_hash(password)
    
    # ensure username is unique (case insensitive)
    user = User.query.filter(User.user_name.ilike(user_name)).first()

    if user:
        flash('The username {} is already in use. Please select another username.'.format(user_name))
        return redirect('/')

    else:
        new_user = add_user(user_name=user_name, password=password, 
                            first_name=first_name, last_name=last_name, email=email)
        login_user(new_user)
        # @todo needs to be broken out for future implementation of multiple users
        # @todo needs to check for duplicate businesses
        if business_name:
            # if a business name was entered, create that business and associate with this user
            new_business = add_business(business_name=business_name,
                                business_street='',
                                business_city='',
                                business_state='',
                                business_zip='',
                                business_phone='',
                                url='',
                                license='')
            new_user.update_user(business_id=new_business.id)
            return redirect('/business/{}'.format(current_user.business_id))
        else:
            return redirect('/business')
コード例 #34
0
def registration(first_msg_obj, conn):
    # Check structure of first_msg_obj
    expected = ["reg"]
    real = sorted(list(first_msg_obj.keys()))
    if expected != real:
        print("Invalid message structure")
        put_message(conn, '{"error": "Invalid message structure"}')
        return

    parted_obj = first_msg_obj["reg"]
    # Check structure of parted_obj
    expected = ["iv", "part1", "part2"]
    real = sorted(list(parted_obj.keys()))
    if expected != real:
        print("Invalid message structure")
        put_message(conn, '{"error": "Invalid message structure"}')
        return

    # Decrypt part1
    globalized.debug("about to decrypt part1")
    part1_b64 = parted_obj["part1"]
    tup, error = part1_parts(part1_b64)
    if error:
        put_message(conn, error)
        return
    ts, username, secret_key, secret_key_b64 = tup
    ts_int = None
    try:
        ts_int = int(ts)
    except ValueError:
        print("timestamp is not int")
        put_message(conn, '{"error": "timestamp is not int"}')
        return

    globalized.debug("about to check time and username")
    now = int(time.time())
    if not (now - 2 * 60 < ts_int < now + 1 * 60):
        print("timestamp out of acceptable range")
        put_message(conn, '{"error": "timestamp out of acceptable range"}')
        return

    user = model.get_user(username)
    if user:
        print("username already exists")
        put_message(conn, '{"error": "username already exists"}')
        return

    # Get iv
    iv_b64 = parted_obj["iv"]
    iv, error = iv_from_b64(iv_b64)
    if error:
        put_message(conn, error)
        return

    # Decrypt part2
    globalized.debug("about to decrypt part2")
    part2_b64 = parted_obj["part2"]
    tup, error = part2_parts(part2_b64, secret_key, iv)
    if error:
        put_message(conn, error)
        return

    certificate, signature = tup

    # Verify signature
    to_hash = (ts + username + secret_key_b64).encode()
    pub_key = certificate.public_key()
    try:
        pub_key.verify(signature, to_hash, padding.PKCS1v15(), hashes.SHA256())
    except InvalidSignature:
        print("Invalid signature of part1")
        put_message(conn, '{"error": "Signature of part1 was invalid"}')
        return

    DH_parameters = dh.generate_parameters(5, 2048)
    DH_private = DH_parameters.generate_private_key()
    DH_public = DH_private.public_key()
    A = DH_public.public_numbers().y
    numbers = DH_parameters.parameter_numbers()
    g = numbers.g
    N = numbers.p

    to_sign = (ts + str(g) + str(N) + str(A)).encode()
    signature = sign_to_b64(to_sign)

    content_dic = {
        "ts": ts,
        "g": str(g),
        "N": str(N),
        "A": str(A),
        "signature": signature
    }
    content_bytes = json.dumps(content_dic).encode()
    iv2 = os.urandom(16)
    enc_content_b64 = aes_encrypt_to_b64(content_bytes, secret_key, iv2)

    msg_2_dic = {
        "content": enc_content_b64,
        "iv": base64.b64encode(iv2).decode()
    }
    msg_2 = json.dumps(msg_2_dic) + "\n"
    put_message(conn, msg_2)

    # Receive 3rd message
    message = None
    try:
        message = get_message(conn)
    except Exception as e:
        print(f"problem receiving 3rd message: {e}")
        put_message(conn, '{"error": "invalid 3rd message"}')
        return

    globalized.debug("checking parts of 3rd message")
    parts, error = parts_3rd_message(message, secret_key, pub_key)
    if error:
        put_message(conn, error)
        return

    B, new_username, new_ts = parts
    if new_username != username:
        print("username in 3rd message doesn't match")
        put_message(conn, '''{"error": "username doesn't match"}''')
        return
    if new_ts != ts:
        print("ts in 3rd message doesn't match")
        put_message(conn, '''{"error": "ts doesn't match"}''')
        return

    peer_public_numbers = dh.DHPublicNumbers(int(B), numbers)
    peer_public_key = peer_public_numbers.public_key()
    secret = DH_private.exchange(peer_public_key)

    # Store username, secret and certificate bytes
    res = model.add_user(username, secret,
                         certificate.public_bytes(serialization.Encoding.DER))

    # Send 4th message
    globalized.debug("preparing 4th message")
    resp = "OK" if res else "NO"
    to_sign = (ts + resp).encode()
    signature = sign_to_b64(to_sign)
    content_dic = {"ts": ts, "resp": resp, "signature": signature}
    content_bytes = json.dumps(content_dic).encode()
    iv4 = os.urandom(16)
    enc_content_b64 = aes_encrypt_to_b64(content_bytes, secret_key, iv4)

    msg_4_dic = {
        "content": enc_content_b64,
        "iv": base64.b64encode(iv4).decode()
    }
    msg_4 = json.dumps(msg_4_dic) + "\n"
    put_message(conn, msg_4)
コード例 #35
0
def registration(name, age, phone, addr, email, uname, pword):
	res = model.check_username(uname)
	if (res is None):
		model.add_user(name, age, phone, addr, email, uname, pword)
	else:
		print("Username already exists..\n\n\n\n")
コード例 #36
0
def fill_users():
    with open('MOCK_DATA.json') as f:
        mock = json.load(f)
    for i in mock:
        add_user(**i)
コード例 #37
0
def create_account(username, password, name):
    if model.check_user(username) == None:
        model.add_user(username, password, name, 100000)
        return 1
    else:
        return 0
コード例 #38
0
ファイル: wishlist.py プロジェクト: brightman/wishlist
 def POST(self):
     data = web.data()#POST data
     model.add_user(uuid,name,sex)
     buf = json.dumps({'uid':uid})
     web.header('Content-Type','application/json')
     return buf