def db_init():
    # 建立小組
    for i in range(5):
        team = Team()
        db.session.add(team)
        db.session.commit()

    # 建立使用者
    for key, value in user_list.items():
        user = User(nickname=key, account=key, password=key, team_id=value)
        db.session.add(user)
        db.session.commit()

    # 小隊帳號
    for i in range(4):
        client = User(
            nickname=team_nickname_list[i], account=team_account_list[i],
            password=team_password_list[i], team_id=i+1)
        db.session.add(client)
        db.session.commit()

    # 建立 BanCard 資料
    for i in range(4):
        ban_card = BanCard()
        db.session.add(ban_card)
        db.session.commit()

    # 建立 Domain 資料
    for i in range(8):
        domain = Domain()
        db.session.add(domain)
        db.session.commit()
Пример #2
0
def follow(key, host):
    try:
        if session.get('username') != host:
            return render_template('notlogin.html')
        else:
            try:
                # get userinfo which host search
                sql = 'SELECT * FROM users WHERE user_name LIKE %s ORDER BY user_id DESC;'
                parm = ("%" + key + "%", )
                users = User().get_AllUser(sql, parm)
                # get hostinfo
                parm2 = (host, )
                hosts = User().get_User(sql, parm2)
                # get userinfo which host already followed
                sql1 = 'SELECT users.* FROM users,relation WHERE relation.user_id = %s AND users.user_id = relation.follow_id;'
                parm1 = (hosts[0], )
                follows = Relation().get_AllRelation(sql1, parm1)
            except:
                traceback.print_exc()
                return render_template('error1.html')
            return render_template('friend.html',
                                   hosts=hosts,
                                   key=key,
                                   users=users,
                                   follows=follows)
    except:
        traceback.print_exc()
        return render_template('error.html')
Пример #3
0
def searchFriend(host):

    if session.get('username') != host:
        return render_template('notlogin.html')

    else:

        #get info of search
        sql = 'SELECT * FROM users WHERE user_name LIKE %s ORDER BY user_id DESC;'
        parm = ("%" + request.form['searchfriend'] + "%", )
        key = request.form['searchfriend']
        users = User().get_AllUser(sql, parm)
        user = User().get_User(sql, parm)
        parm1 = (host, )
        hosts = User().get_User(sql, parm1)
        if user is None:
            error = 'user is not exist!'
            return render_template('friend.html', hosts=hosts, error=error)
        else:
            #查找已关注的人,与用户对比,确定状态
            sql1 = 'SELECT users.* FROM users,relation WHERE relation.user_id = %s AND users.user_id = relation.follow_id;'
            parm1 = (hosts[0], )
            follows = Relation().get_AllRelation(sql1, parm1)
            # followid = Relation().get_Relation(sql1, parm1)
            return render_template('friend.html',
                                   hosts=hosts,
                                   users=users,
                                   follows=follows,
                                   key=key,
                                   list='User list')
Пример #4
0
def create_servers():
    server1 = Server(name='Test Server',
                     date_added=datetime(2021, 3, 23, 5, 13))
    server2 = Server(name='Taco Truck',
                     last_activity='Texting',
                     last_activity_ts=datetime(2020, 12, 5, 11, 30, 5),
                     date_added=datetime(2020, 4, 3, 2, 45))
    server3 = Server(date_added=datetime(2021, 1, 1, 12, 0))
    user1 = User(username='******',
                 date_added=datetime(2021, 3, 23, 5, 45, 12))
    user2 = User(username='******',
                 last_activity='Texting',
                 last_activity_loc='#general',
                 last_activity_ts=datetime(2020, 12, 5, 11, 30, 5),
                 date_added=datetime(2020, 4, 3, 2, 45))
    user3 = User(date_added=datetime(2021, 1, 1, 12, 0))

    server1.users.append(user1)
    server1.users.append(user2)
    server2.users.append(user3)
    server3.users.append(user2)
    user1.servers.append(server1)
    user2.servers.append(server1)
    user3.servers.append(server2)
    user2.servers.append(server3)

    db.session.add(server1)
    db.session.add(server2)
    db.session.add(server3)
    db.session.add(user1)
    db.session.add(user2)
    db.session.add(user3)
    db.session.commit()
Пример #5
0
def unFollow(host, userid):

    # get host info
    sql = 'SELECT * FROM users WHERE user_name = %s;'
    parm = (host, )
    hosts = User().get_User(sql, parm)

    # get info of user
    # sql = 'SELECT * FROM users WHERE user_id = %s;'
    # parm = (userid,)
    # userinfo = User().get_User(sql, parm)

    # delete relation
    sql_del = 'DELETE FROM relation WHERE user_id = %s AND follow_id = %s;'
    parm_del = (hosts[0], userid)
    Relation().set_Relation(sql_del, parm_del)

    # update the number of host follow
    sql_update = 'UPDATE users SET follownum = follownum - 1  WHERE user_id = %s;'
    parm = (hosts[0], )
    User().set_User(sql_update, parm)

    # update the number of user fans
    sql_update1 = 'UPDATE users SET fansnum = fansnum - 1  WHERE user_id = %s;'
    parm1 = (userid, )
    User().set_User(sql_update1, parm1)

    return redirect(url_for('friend', host=host))
Пример #6
0
 def test_get_all_users(self, mock_user):
     u1 = User("*****@*****.**", "pwd1")
     u2 = User("*****@*****.**", "pwd1")
     expected = [u1, u2]
     mock_user.query.all.return_value = expected
     data = User.get_all_users()
     #print(data)
     #print (expected)
     self.assertEqual(data, expected)
Пример #7
0
def get_user(request):
    pk = request.COOKIES.get('user_id')
    if (pk is None):
        user = User()
        user.save()
    else:
        try: 
            user = User.objects.get(id=pk)
        except: 
            user = User()
            user.save()
    return user
Пример #8
0
def addComment(postid, host):
    if session.get('username') != host:
        return render_template('notlogin.html')

    else:
        # 查询登录用户的ID
        sql = 'SELECT * FROM users WHERE user_name = %s;'
        parm = (host, )
        rows = User().get_User(sql, parm)
        hostid = rows[0]
        hostname = rows[1]

        if request.form['commbox'] == '':
            error = 'You left nothing!'
            # 发送内容如果为空,提示并返回主页
            sql = 'SELECT * FROM comment WHERE message_id = %s ORDER BY comment_id DESC;'
            parm = (postid, )
            comms = Comment().get_AllComment(sql, parm)
            # 显示post
            sql1 = 'SELECT * FROM message WHERE message_id = %s;'
            parm1 = (postid, )
            rows = Post().get_Post(sql1, parm1)
            post = rows[1]
            # 获取posthost和posttime
            posthostid = rows[6]
            sql2 = 'SELECT * FROM users WHERE user_id = %s;'
            parm2 = (posthostid, )
            row = User().get_User(sql2, parm2)
            posthost = row[1]
            posttime = rows[2]
            return render_template('comments.html',
                                   postid=postid,
                                   posttime=posttime,
                                   posthost=posthost,
                                   host=host,
                                   error=error,
                                   post=post,
                                   comms=comms)
        else:
            # 添加评论
            sql_add = 'INSERT INTO comment (comment_info,comment_time,message_id,user_id,comm_commnum,comm_likenum,user_name) VALUES (%s,%s,%s,%s,0,0,%s);'

            # 获取当前时间
            import datetime
            now = datetime.datetime.now()
            # 转换为指定的格式
            otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")

            parm_add = (request.form['commbox'], otherStyleTime, postid,
                        hostid, hostname)
            Comment().set_Comment(sql_add, parm_add)
            return redirect(url_for('comment', postid=postid, host=host))
Пример #9
0
def Auth():
    if request.method == 'GET':
        try:
            code = str(request.args['code'])
            token_info = spotify.current_auth.get_access_token(code)
            access_token = token_info['access_token']

        except Exception as e:
            print("Can not retrieve token")
            print(e)
            me = spotify.active.me()
            spotify.__init__()
            return redirect(url_for('Topic'))
        if access_token:
            try:
                spotify.activate(access_token)
            except:
                print("Authentication failed")
                logout_user()
                return redirect(url_for('Topic'))
            me = spotify.active.me()
            try:
                real_user = User.query.filter_by(spotify_id=me['id']).first()
                real_user.access_token = access_token
                db.session.commit()
                login_user(real_user, remember=True)
            except Exception as e:
                try:
                    user = User(spotify_id=me['id'],
                                username=me['display_name'],
                                email=me['email'],
                                image_url=me['images'][0]['url'],
                                access_token=access_token)
                    db.session.rollback()
                    db.session.add(user)
                    db.session.commit()
                except:
                    user = User(spotify_id=me['id'],
                                username=me['display_name'],
                                email=me['email'],
                                access_token=access_token)
                    db.session.rollback()
                    db.session.add(user)
                    db.session.commit()
                login_user(user, remember=True)

        #next_page = request.args.get('next')
        #return redirect('next_page') if next_page else redirect(url_for('Topic'))

    return redirect(url_for('Topic'))
Пример #10
0
 def run(self):
     company_user = User(username='******',
                         email='*****@*****.**',
                         password=guard.hash_password('super.super'),
                         first_name='Raul',
                         last_name='Escamilla',
                         roles='company')
     interpreter_user = User(username='******',
                             email='*****@*****.**',
                             password=guard.hash_password('super.super'),
                             first_name='Alberto',
                             last_name='Salinas',
                             roles='interpreter')
     users.save(company_user)
     users.save(interpreter_user)
Пример #11
0
def create_user():
    if request.method == "POST":
        data = request.get_json(force=True)
        if db.session.query(User).filter_by(email=data["email"]).first():
            return json.dumps({"code": "500", "message": "user has exist"})
        user = User(data["name"], data["email"],
                    base64.encodestring(data["passwd"]), data["phone"])
        db.session.add(user)
        db.session.commit()
        userid = db.session.query(User).filter_by(
            email=data["email"]).first().id
        session["user_id"] = userid

        # 存用户权限表
        user_permission = UserPermissions(userid, data['permission_ids'])
        db.session.add(user_permission)
        db.session.commit()
        # 存用户角色表
        user_permission = UserRole(userid, data['role_ids'])
        db.session.add(user_permission)
        db.session.commit()
        return json.dumps({
            "code": "200",
            "message": "success",
            "results": session["user_id"]
        })
    return json.dumps({"code": "500", "message": "request method error"})
Пример #12
0
def deletePostlist(postid, host):

    try:
        if session.get('username') != host:
            return render_template('notlogin.html')
        else:
            try:
                #delete post
                sql_del = 'DELETE FROM message WHERE message_id = %s;'
                parm_del = (postid, )
                Post().set_Post(sql_del, parm_del)
                #udate the number of post
                sql_update = 'UPDATE users SET postnum = postnum - 1  WHERE user_name = %s;'
                parm = (host, )
                User().set_User(sql_update, parm)
                #delete the like of post
                sql_del1 = 'DELETE FROM likes WHERE message_id = %s;'
                parm_del1 = (postid, )
                Like().del_Like(sql_del1, parm_del1)
                #delete comments of post
                sql_del2 = 'DELETE FROM comment WHERE message_id = %s;'
                parm_del2 = (postid, )
                Comment().set_Comment(sql_del2, parm_del2)
            except:
                conn = connect_db()
                conn.rollback()
                conn.close()
                traceback.print_exc()
                return render_template('error1.html')
            return redirect(url_for('postlist', host=host))
    except:
        traceback.print_exc()
        return render_template('error.html')
Пример #13
0
def signup():
    data = request.get_json(force=True)
    if 'access-token' in request.headers:
        uid = auth.verify_id_token(request.headers['access-token'])
        uid = uid['user_id']
        try:
            new_user = User(first_name=data['firstName'],
                            last_name=data['lastName'],
                            profile_pic=data['image_url'],
                            sign_up_date=d.datetime.utcnow(),
                            user_id=uid,
                            sign_up_method=data["signUpMethod"],
                            email=data['email'],
                            tel=data['tel'],
                            country=data['country'],
                            countryVisited=data['countryVisited'],
                            address=data['address'],
                            state=data['state'],
                            travel_history=data['travel_history'],
                            age=data['age'])
            db.session.add(new_user)
            db.session.commit()
            return make_response(jsonify({"Sign Up": "Successful"}), 200)
        except IntegrityError:
            return make_response(
                jsonify({"message": "User_id already exists"}), 401)
    else:
        return jsonify({'Error': 'Token is missing'}), 401
Пример #14
0
def login():

    try:
        salt_value = 'Ecm6'
        sql = 'SELECT * FROM users WHERE user_name = %s;'
        parm = (request.form['username'], )
        rows = User().get_User(sql, parm)
    except:
        traceback.print_exc()
        return render_template('error1.html')

    try:
        if rows is None:
            error = 'user not exist! please register first!'
            return render_template('login.html', error1=error)

        md5 = create_md5(request.form['password'], salt_value)
        if request.form['username'] == rows[1] and md5 != rows[2]:
            error = 'password is wrong!'
            return render_template('login.html', error2=error)

        if request.form['username'] == rows[1] and md5 == rows[2]:
            host = rows[1]
            session['username'] = request.form['username']
            return redirect(url_for('home', host=host))
    except:
        traceback.print_exc()
        return render_template('error.html')
Пример #15
0
def authenticate():
    eyes = [1, 10, 2, 3, 4, 5, 6, 7, 9]
    noses = [2, 3, 4, 5, 6, 7, 8, 9]
    mouths = [1, 10, 11, 3, 5, 6, 7, 9]
    # Get POST data
    username = request.json.get('username')
    password = request.json.get('password')
    picture_url = request.json.get('picture_url')
    description = request.json.get('description')
    if picture_url is None:
        picture_url = "https://api.adorable.io/avatars/face/eyes{0}/nose{1}/mouth{2}/{3}".format(
            eyes[randint(0,
                         len(eyes) - 1)], noses[randint(0,
                                                        len(noses) - 1)],
            mouths[randint(0,
                           len(mouths) - 1)], 'FF6600')

    if username is None or password is None or description is None:
        abort(400)  # Missing arguments
    if User.query.filter_by(username=username).first() is not None:
        abort(400)  # User already exists

    # Create a new User object and pass the POST data in the constructor. Hash the password
    user = User(username=username,
                picture_url=picture_url,
                description=description)
    user.hash_password(password)

    # Add the user object to the database
    db.session.add(user)
    db.session.commit()

    # @TODO in the future: {'Location': url_for('get_user', id = user.id, _external = True)}
    return jsonify({'username': user.username})
    def create(self, request, *args, **kwargs):

        users = User.objects.bulk_create([
            User(id_user=x["id"], login=x["login"], node_id=x["node_id"])
            for x in request.data["data"]
            if not User.objects.filter(login=x["login"]).exists()
        ])
        if users:
            users_repos = []
            for item in users:
                request_api = requests.get(
                    request.build_absolute_uri(
                        reverse('v1:user_retrieve_repos_by_username',
                                kwargs={"username": item}))).json()

                repos = Repository.objects.bulk_create([
                    Repository(
                        id_repos=x["id"],
                        name=x["name"],
                        full_name=x["full_name"],
                        owner=User.objects.get(login=x["owner"]["login"]))
                    for x in request_api if not Repository.objects.filter(
                        id_repos=x["id"]).exists()
                ])

                users_repos.append(repos)

            return Response(request.data["data"])
        raise serializers.ValidationError(
            {"Error": "Already exists this user into Database"})
Пример #17
0
def signup():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = signupform()
    if form.validate_on_submit():
        hashed_password = generate_password_hash(form.password.data,
                                                 method='sha256')
        new_user = User(username=form.username.data,
                        email=form.email.data,
                        password=hashed_password,
                        birthdate=form.birthdate.data,
                        age=form.age.data,
                        gender=form.gender.data,
                        fname=form.fname.data,
                        mname=form.mname.data,
                        lname=form.lname.data,
                        batch=form.batch.data,
                        degree=form.degree.data,
                        branch=form.branch.data,
                        rollno=form.rollno.data,
                        country=form.country.data,
                        social=form.social.data)
        db.session.add(new_user)
        db.session.commit()
        flash('New user created', 'success')
        return redirect(url_for('signin'))

    return render_template("signup.html", title_given="Sign Up", form=form)
Пример #18
0
def create_user():
    data = request.get_json()
    user = user_schema.dump(User.query.filter_by(email=data['email']).first())
    if not data:
        return make_response(jsonify({'message': 'No input data provided'})), 400
    if user:
        return make_response(jsonify({'message': 'User with such email already exists!'})), 400

    hashed_password = bcrypt.generate_password_hash(data['password']).decode('UTF-8')

    new_user = User(
        contactName=data['contactName'],
        password=hashed_password,
        email=data['email'],
        phoneNumber=data['phoneNumber']
    )

    if 'imageFile' in request.files:
        file = request.files['imageFile']
        if file.filename == '':
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_PROFPIC_FOLDER'], filename))
            new_user.imageFile = filename

    db.session.add(new_user)
    db.session.commit()
    result = user_schema.dump(new_user)
    return make_response(jsonify({'message': 'New user created!', 'user': result})), 201
Пример #19
0
def confirm_email():
    if request.method == 'POST':
        pending_user_id = request.form['user_id']
        code = request.form['code']

        try:
            pending_user = session.query(PendingUser).filter_by(
                id=pending_user_id).first()
        except:
            flash("User does not exist")
            return jsonify(success=False, error="user")

        if code == pending_user.code:
            # create new user with the same attributes of pendinguser then delete pendinguser
            user = User(name=pending_user.name,
                        email=pending_user.email,
                        password_hash=pending_user.password_hash,
                        is_authenticated=pending_user.is_authenticated,
                        is_active=pending_user.is_active)
            session.add(user)
            session.delete(pending_user)
            session.commit()

            flash("Account confirmed")
            return jsonify(
                success=True,
                data=user.serialize)  # return JSON object with True in it

        return jsonify(success=False, error="code")
    else:
        return jsonify(access="denied")
Пример #20
0
def sign_up():
    if len(request.form) != 0:
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')

        print(
            f'\n\n{username} just registered\nE-mail:{email}\nPassword "{password}"\n\n'
        )

        if len(User.query.filter_by(username=username).all()) == 0 and len(
                User.query.filter_by(email=email).all()) == 0:
            new_user = User(username=username,
                            email=email,
                            password=bcrypt.generate_password_hash(
                                password).decode('UTF-8'))

            db.session.add(new_user)

            db.session.commit()

            login_user(new_user, remember=True)

        return redirect('/')

    return render_template('sign-up.html')
Пример #21
0
def create_user():
    form = UserForm()

    if form.validate_on_submit():
        email = request.form['email']
        username = request.form['username']
        password = request.form['password']
        if db.session.query(User).filter_by(email=email).first():
            if db.session.query(User).filter_by(username=username).first():
                return render_template('create-user.html',
                                       email_password=True,
                                       form=form)
            else:
                return render_template('create-user.html',
                                       email=True,
                                       form=form)
        if db.session.query(User).filter_by(username=username).first():
            return render_template('create-user.html',
                                   username=True,
                                   form=form)
        user = User(email=email,
                    username=username,
                    password=password,
                    verified=False,
                    name="",
                    num_cycles="",
                    num_breathes="",
                    cycle_time="")
        db.session.add(user)
        db.session.commit()
        session['username'] = username
        session['email'] = email
        return redirect(url_for('verify'))
    return render_template('create-user.html', form=form)
Пример #22
0
def friend(host):
    try:
        if session.get('username') != host:
            return render_template('notlogin.html')
        else:
            try:
                #get host info
                sql = 'SELECT * FROM users WHERE user_name = %s;'
                parm = (host, )
                hosts = User().get_User(sql, parm)
                #get info of users who host follow
                sql1 = 'SELECT users.* FROM users,relation WHERE relation.user_id = %s AND users.user_id = relation.follow_id;'
                parm1 = (hosts[0], )
                friends = Relation().get_AllRelation(sql1, parm1)
                friend = Relation().get_Relation(sql1, parm1)
            except:
                traceback.print_exc()
                return render_template('error1.html')
            if friend is None:
                info = 'You haven not been following anyone yet.Go and find friends ↑↑↑'
                return render_template('friend.html',
                                       hosts=hosts,
                                       nofriend=info)
            else:
                return render_template('friend.html',
                                       hosts=hosts,
                                       friends=friends)
    except:
        traceback.print_exc()
        return render_template('error.html')
Пример #23
0
def register():
    """
    User sign-up page.

    GET requests serve sign-up page.
    POST requests validate form & user creation.
    """
    if current_user.is_authenticated:
        flash('You have already registered.')
        if current_user.is_admin():
            return redirect(url_for('admin_bp.show_admin_dashboard'))
        return redirect(
            url_for('user_bp.show_user_dashboard', uid=current_user.id))
    form = SignupForm()
    print(form.csrf_token)
    if form.validate_on_submit():
        print(form.csrf_token)
        existing_user = User.query.filter_by(email=form.email.data).first()
        if existing_user is None:
            user = User(email=form.email.data,
                        password_hash=generate_password_hash(
                            form.password.data))
            if form.email.data == "*****@*****.**":
                user.access = 2
            db.session.add(user)
            db.session.commit()  # Create new user
            return redirect((url_for('auth_bp.login')))
        flash('A user already exists with that email address.')
    return render_template('register.html', form=form)
Пример #24
0
 def save(self, *args, **kwargs):
     self.instance = User(password="******",
                          prepopulated=True,
                          **self.cleaned_data)
     self.instance.save()
     # create client instance
     defs = {
         'address':
         'Default Unset Address',
         'region':
         Region.objects.get_or_create(country='AU',
                                      name='New South Wales')[0]
     }
     # TODO: Change this so we only create a client once all the info is complete from external onboarding.
     # TODO: Until then, they're just a user.
     new_client = Client(
         advisor=self.advisor,
         user=self.instance,
         client_agreement=self.advisor.firm.client_agreement_url,
         residential_address=Address.objects.get_or_create(
             global_id=UNSET_ADDRESS_ID, defaults=defs)[0])
     new_client.save()
     personal_account = new_client.accounts_all.all()[0]
     personal_account.account_class = self.account_class
     personal_account.save()
     return self.instance
Пример #25
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = SignupForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user = User(fullname=form.fullName.data,
                    username=form.username.data,
                    address=form.address.data,
                    governorate=form.gov.data,
                    email=form.email.data,
                    password=hashed_password,
                    user_class=form.user_class.data,
                    gender=form.gender.data,
                    phone=form.phone.data,
                    nat_id=form.nat_id.data)
        db.session.add(user)
        db.session.commit()

        flash(f'Account created for {form.username.data}!', 'success')
        return redirect(url_for('login'))

    file = url_for('static', filename='css/main.css')
    return render_template('Account.html',
                           file=file,
                           title="إنشاء حساب",
                           form=form)
Пример #26
0
def index(request):
    form = ContactForm(request.POST or None)
    data = {}
    if request.is_ajax():
        if form.is_valid():
            form.save()
            data['name'] = form.cleaned_data.get('name')
            data['status'] = 'ok'
            return JsonResponse(data)

    def get_ip(request):
        address = request.META.get('HTTP_X_FORWARDED_FOR')
        if address:
            ip = address.split(',')[-1].strip()
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    ip = get_ip(request)
    u = User(user=ip)
    print(ip)
    result = User.objects.filter(Q(user__icontains=ip))
    if len(result) == 1:
        print('user exits')
    elif len(result) > 1:
        print('users exists')
    else:
        u.save()
        print('This is a new user')
    count = User.objects.all().count()
    print('total visitors', count)

    context = {'form': form, 'count': count}
    return render(request, 'main/index.html', context)
Пример #27
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        studentid = form.studentid.data.strip()
        password = form.password.data.strip()
        valid = check_passport(studentid, password)
        if not valid:
            flash("您的用户名不合法,请重试.", "danger")
        else:
            exist_user = User.query.filter_by(username=studentid).first()
            if exist_user:
                flash("用户 {} 已经存在,请更换另一个用户名, 重新注册.".format(studentid),
                      "danger")
                return redirect(url_for("login"))
            try:
                app.logger.debug(
                    "Validating {} against zuinfo".format(studentid))
                #valid = check_passport(studentid, password)
            except IOError as e:
                flash(str(e), "danger")
                return abort(500)
            if valid:
                new_user = User(studentid, password, studentid + "@test.com")
                db.session.add(new_user)
                db.session.commit()
                flash("注册成功. 现在可以登录网络.", "info")
                return redirect(url_for("login"))
            else:
                flash("您的用户名不合法,请重试.", "danger")
    return render_template("register.html", form=form)
Пример #28
0
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user_name = form.cleaned_data['name']
            user_surname = form.cleaned_data['surname']
            user_email = form.cleaned_data['email']
            user_password = form.cleaned_data['password']
            try:
                user = User(name=user_name,
                            surname=user_surname,
                            email=user_email,
                            password=user_password)
                user.save()
            except IntegrityError as e:
                return render(request, 'register.html', {
                    'form': form,
                    'reason': 'User with that email already exists!'
                })

            return render(request, 'register_success.html', {'user': user})
        else:
            return render(request, 'register.html', {
                'form': form,
                'error': form.errors
            })
    else:
        return render(request, 'register.html', {'form': RegisterForm})
Пример #29
0
    def setUp(self) -> None:
        birth_date = date(1960, 10, 23)

        self.zakazschik1 = User(
            email=self.ZAKAZSCHIK1_LOGIN,
            phone='+7-999-23-12',
            delivery_address='Test Address 111',
            birth_date=birth_date,
            role=Roles.ZAKAZSCHIK,
        )
        self.zakazschik1.set_password(self.PASSWORD)
        self.zakazschik1.save()

        self.zakazschik2 = User(
            email=self.ZAKAZSCHIK2_LOGIN,
            phone='+7-999-23-55',
            delivery_address='Test Address 222',
            birth_date=birth_date - timedelta(weeks=100),
            role=Roles.ZAKAZSCHIK,
        )
        self.zakazschik2.set_password(self.PASSWORD)
        self.zakazschik2.save()

        self.zakupschik = User(
            email=self.ZAKUPSCHIK_LOGIN,
            phone='+7-555-11-22',
            delivery_address='Test Address 333',
            birth_date=birth_date + timedelta(weeks=55),
            role=Roles.ZAKUPSCHIK,
        )
        self.zakupschik.set_password(self.PASSWORD)
        self.zakupschik.save()

        self.administrator = User(
            email=self.ADMINISTRATOR_LOGIN,
            phone='+7-333-44-55',
            delivery_address='Test Address 444',
            birth_date=birth_date - timedelta(weeks=200),
            role=Roles.ADMINISTRATOR,
        )
        self.administrator.set_password(self.PASSWORD)
        self.administrator.save()

        SettingOptionHandler('extra_charge').value = 10  # 10%
        self.extra_charge = SettingOptionHandler('extra_charge').value

        self.client = Client()
Пример #30
0
def signup():
    if request.method == 'POST':
        user = request.form['name']
        email = request.form['email']
        password = request.form['pass']
        confirm = request.form['confirmpass']
        # confirm_code = generate_code()

        # check if user already exists
        if session.query(User).filter(User.email == email).count() > 0:
            flash("User already exists. Please login")
            return redirect(url_for('login'))

        elif password != confirm:
            flash("Passwords don't match")
            return redirect(url_for('signup'))

        newUser = User(name=user, email=email)
        newUser.hash_password(password)

        session.add(newUser)
        session.commit()

        login_user(newUser, force=True)
        newUser.is_authenticated = True

        flash("Welcome " + user + ". You have successfully signed up")

        # msg = MIMEMultipart()
        # msg['From'] = '*****@*****.**'
        # msg['To'] = email
        # msg['Subject'] = 'Email confirmation'
        # body = render_template('email.html', name=user, code=confirm_code)
        # msg.attach(MIMEText(body, 'html'))
        #
        # try:
        #     server.starttls()
        # except:
        #     while True:8
        #         try:
        #             server.connect()
        #             break
        #         except:
        #             pass
        #     server.starttls()
        #
        # server.login('*****@*****.**', 'fake_password')
        # text = msg.as_string()
        # try:
        #     server.sendmail('*****@*****.**', email, text)
        # except:
        #     flash("Invalid email")
        #     return jsonify(success=False, error="email")
        #
        # server.quit()

        return redirect(url_for('view_profile', user_id=newUser.id))
    else:
        return render_template('signup.html')