Beispiel #1
0
 async def login(request):
     name = request.form.get('name')
     password = request.form.get('password')
     if name == 'demo' and password == '1234':
         auth.login_user(request, User(id=1, name=name))
         return response.text('okay')
     return response.text('failed')
Beispiel #2
0
async def login(request):
    print('/admin/login')
    if request.method == 'GET':
        return template('login.html', error="请输入用户名或者密码")
    phone = request.form.get('username')
    password = request.form.get('password')
    print(phone, password)

    md5 = MD5(password.encode("utf8"))
    users = None
    try:
        #step 1
        users = AdminUser.select().where(AdminUser.phone == phone)
        #step 2
        if users.count() >= 1:
            baseuser = users.get()
            if baseuser.password != md5:
                print(baseuser.password + ':' + md5 + " is not equal.")
                return template('login.html', error="请输入正确的密码")
            user = User(id=baseuser.phone, name=baseuser.password)
            auth.login_user(request, user)
            #return redirect('/admin/news/admin')
            return template('index.html')
        else:
            return template('login.html', error="用户名不正确")
    except Exception as e:
        return template('login.html', error="用户名或密码不正确")
Beispiel #3
0
async def login(request):
    page = dict()
    lform = LoginForm(request)
    if request.method == 'POST' and lform.validate():
        fuser = lform.username.data
        fpass = lform.password.data
        data = (f'SELECT * FROM "blog_users" WHERE `username`="{fuser}" AND `password`="{fpass}";', 1)
        fetch = await sql_master(data)
        if fetch is not None:
            user = User(id=1, name=fuser)
            auth.login_user(request, user)
            page['title'] = 'Login'
            page['header'] = 'Thank you for logging in!'
            page['text'] = 'Redirecting in 3 seconds...'
            return jrender('page.html', request, page=page,
                           js_head_end='<script defer>window.setTimeout(function(){ window.location = "admin"; },3000);'
                                       '</script>')
        else:
            page['error'] = 'Login Failed. Please Try Again.'
    login_check = request['session'].get('username')
    if login_check is None:
        page['title'] = 'Login'
        page['header'] = 'Restricted Area - Login Required'
        return jrender('page.html', request, page=page, form=lform,
                       css_head_end='<style>.mdl-layout{align-items: center;justify-content: center;}'
                                    '.mdl-layout__content {padding: 24px;flex: none;}</style>')
    page['title'] = 'Login'
    page['header'] = 'You\'re already logged in!'
    page['text'] = 'Redirecting in 3 seconds...'
    return jrender('page.html', request, page=page,
                   js_head_end='<script defer>window.setTimeout(function(){ window.location = "admin"; },3000);'
                               '</script>')
async def login(request):
    """Authenticate a user

    Checks and authenticates a user and saves into session. 
    Redirects to the main page on corrent login,
    else displays error message.
    """

    username = request.form.get('username')
    password = request.form.get('password')

    with open("www/login.html", "r", encoding='utf-8') as f:
        login = f.read()
    with open("www/style.css", "r", encoding='utf-8') as f:
        style = f.read()

    q = Query()
    result = next(
        iter(db.search((q.username == username) & (q.password == password))),
        None)
    if result:
        user = User(id=result.get('id'), name=username)
        auth.login_user(request, user)
        return response.redirect('/')
    else:
        msg_bad_login = '******'
        return response.html(login.format(style, msg_bad_login))
Beispiel #5
0
 async def login(request):
     message = ''
     username = request.form.get('username')
     password = request.form.get('password')
     # fetch user from database
     user = User(id=1, name=username)
     if user:
         auth.login_user(request, user)
         return json({"status": 0, "msg": "%s login success" % username})
Beispiel #6
0
async def setup(request):
    page = dict()
    if config['SETUP_DB']:
        dform = DatabaseForm(request)
        if request.method == 'POST' and dform.validate():
            valid = await sql_validate(dform.user.data, dform.password.data,
                                       dform.name.data, dform.host.data,
                                       dform.type.data)
            if not valid:
                print('Error - DB Not Valid')
                return redirect(app.url_for('setup'))
            config['SETUP_DB'] = False
            return redirect(app.url_for('setup'))
        page['title'] = 'Blog First Start'
        page['header'] = 'Setup Database'
        page[
            'text'] = 'Below you should enter your database connection details.'
        return jrender('page.html', request, page=page, form=dform)
    elif config['SETUP_BLOG']:
        wform = WelcomeForm(request)
        if request.method == 'POST' and wform.validate():
            user = User(id=1, name=wform.username.data)
            auth.login_user(request, user)
            config['SETUP_BLOG'] = False
            uri = config['DB_URI']
            dbt = config['DB_TYPE']
            with open("config.py", "wt") as o:
                o.write(f'DB_URI = {repr(uri)}\n')
                o.write(f'DB_TYPE = {repr(dbt)}\n')
                o.write('DEMO_CONTENT = False\n')
                o.write('SETUP_DB = False\n')
                o.write('SETUP_BLOG = False\n')
            await sql_demo()
            con = await sql_connection()
            date = datetime.datetime.now()
            await con.execute(
                f'INSERT INTO "blog_settings" (`title`,`created_on`,`username`,`password`,`email`,`hidden'
                f'`) VALUES ("{wform.title.data}","{date}","{wform.username.data}","{wform.password.data}'
                f'","{wform.email.data}","{wform.seo.data}");')
            await con.commit()
            await con.close()
            return redirect('/')
        page['title'] = 'Blog First Start'
        page['header'] = 'Welcome'
        page[
            'text'] = 'Before you get blogging, we need to setup a few things.'
        return jrender('page.html', request, page=page, form=wform)
    page['title'] = 'Setup'
    page['header'] = 'Already Completed'
    page['text'] = 'Redirecting in 3 seconds...'
    return jrender(
        'page.html',
        request,
        page=page,
        js_head_end=
        '<script defer>window.setTimeout(function(){ window.location = "/"; },3000);</script>'
    )
Beispiel #7
0
async def setup(request):
    page = dict()
    if config['SETUP_DB']:
        dform = DatabaseForm(request)
        if request.method == 'POST' and dform.validate():
            print('Setting up DB')
            data = (dform.user.data, dform.password.data, dform.name.data, dform.host.data, dform.type.data)
            await sql_master(data)
            # if not valid:
            #     print('Error - DB Not Valid')
            #     return redirect(app.url_for('setup'))
            config['SETUP_DB'] = False
            print('DB Setup Finished')
            return redirect(app.url_for('setup'))
        page['title'] = 'Blog First Start'
        page['header'] = 'Setup Database'
        page['text'] = 'Below you should enter your database connection details.'
        return jrender('page.html', request, page=page, form=dform)
    elif config['SETUP_BLOG']:
        print('Setting up Blog')
        wform = WelcomeForm(request)
        if request.method == 'POST' and wform.validate():
            user = User(id=1, name=wform.username.data)
            auth.login_user(request, user)
            # uri = config['DB_URI']
            # dbt = config['DB_TYPE']
            # with open("config.py", "wt") as o:
            #     o.write(f'DB_URI = {repr(uri)}\n')
            #     o.write(f'DB_TYPE = {repr(dbt)}\n')
            #     o.write('DEMO_CONTENT = False\n')
            #     o.write('SETUP_DB = False\n')
            #     o.write('SETUP_BLOG = False\n')
            # print('Wrote config.py')
            # demo = await sql_demo()
            # print('Injected Demo Content')
            # if not demo:
            #     print('Demo content broke')
            #     return redirect(app.url_for('setup'))
            # print('Finished With Demo Content')
            data = (wform.title.data, wform.username.data, wform.password.data, wform.email.data)
            finish_up = await sql_master(data)
            if not finish_up:
                return redirect(app.url_for('setup'))
            config['SETUP_BLOG'] = False
            return redirect('/')
        page['title'] = 'Blog First Start'
        page['header'] = 'Welcome'
        page['text'] = 'Before you get blogging, we need to setup a few things.'
        return jrender('page.html', request, page=page, form=wform)
    page['title'] = 'Setup'
    page['header'] = 'Already Completed'
    page['text'] = 'Redirecting in 3 seconds...'
    return jrender('page.html', request, page=page,
                   js_head_end='<script defer>window.setTimeout(function(){ window.location = "/"; },3000);</script>')
Beispiel #8
0
async def signup(request):
	try:
		data = request.json.get('form',None)
		username = data.get('username',None)
		password = data.get('password',None)
		name = data.get('name',None)
		email = data.get('email',None)

		assert username and name and password and email is not None

		this_user = await User.find_one({'email':email})
		assert this_user is None
		new_user = User(name=name,username=username,email=email)
		new_user.set_password(password)
		await new_user.commit()
		return response.json({'status':True, 'message':"Signup success"})
	except AssertionError as ae:
		raise ae
		return response.json({'status':False, 'message':"Signup failed, email already exist"})
	except Exception as other_e:
		print(other_e)
		return response.json({'status':False, 'message':"Houston we have a problem here!"})
Beispiel #9
0
async def login(request):
    if request.method == 'POST':
        username = request.json.get('username')
        password = request.json.get('password')
        # login_sql = 'select * from users where username = "******" and password = "******" and page_level = "%s"' % (username, password, page_level)
        login_sql = 'select * from users where username = "******" and password = "******"' % (
            username, password)
        account = await request.app.mysql.query_select(login_sql)
        if len(account) != 0:
            user = User(account[0][0], username, account[0][3])
            auth.login_user(request, user)
            logger.info("User %s login successfully!" % username)
            return response.json({"message": "Login success!"}, status=200)
    return response.json({"message": "Login failed!"}, status=401)
Beispiel #10
0
async def login(request):
    error_message = ""
    if request.method == 'POST':
        password = request.form.get('password', '').encode('utf8')
        for login_hash in login_hashes:
            if bcrypt.checkpw(password, login_hash):
                user = User(id=1, name="name")  # values dont matter
                auth.login_user(request, user)
                return response.redirect('/')
            else:
                error_message = "Incorrect password"

    template = env.get_template('login.html')
    html_content = template.render(error_message=error_message)
    return response.html(html_content)
Beispiel #11
0
async def login(request):
    message = ''
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # for demonstration purpose only, you should use more robust method
        if username == 'demo' and password == '1234':
            # use User proxy in sanic_auth, this should be some ORM model
            # object in production, the default implementation of
            # auth.login_user expects User.id and User.name available
            user = User(id=1, name=username)
            auth.login_user(request, user)
            return response.redirect('/')
        message = 'invalid username or password'
    return response.html(LOGIN_FORM.format(message))
Beispiel #12
0
async def signin(request):
    if request.method == 'POST':
        email = request.form.get('email')
        password = request.form.get('password')

        uid = get_user_id(email=email, password=password)

        if uid:
            user = User(id=uid, name=email)
            auth.login_user(request, user)

            return redirect('/quiz/list')
        else:
            abort(401)
    return render_template('signin.html')
Beispiel #13
0
async def login(request):
    if request.method == 'POST':
        id = request.form.get('id')
        password = request.form.get('password')
        name = request.form.get('name')
        print('id', id, 'pwd', password, 'name', name)

        get_password = await pg_set_get.get_user_password_by_id(id)

        # TODO: redis get_id and get_pwd
        if password == get_password:
            print(password, get_password)
            user = User(id=id, name=name)
            auth.login_user(request, user)

            return response.redirect('/lobby')
        else:
            return {'message': 'LOGIN FAIL'}
    else:
        return {'message': '로그인 페이지입니다'}
Beispiel #14
0
async def login(request):
    message = ''
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        try:
            with connection.cursor() as cursor:
                sql = "SELECT * from login WHERE username  = '******' and password = '******'".format(
                    username, password)
                cur = cursor.execute(sql)
        except Exception as e:
            print(e)
        if cur:
            user = User(id=1, name=username)
            auth.login_user(request, user)
            return response.redirect('/')
        message = 'invalid username or password'
    template = env.get_template('login.html')
    html_content = template.render(message=message)
    return response.html(html_content)
Beispiel #15
0
async def login(request):
    form = LoginForm(request)
    errors = {}
    if request.method == 'POST' and form.validate():
        username = form.username.data
        password = form.password.data
        try:
            user = await db_objects.get(Operator, username=username)
            if await user.check_password(password):
                login_user = User(id=user.id, name=user.username)
                auth.login_user(request, login_user)
                return response.redirect("/")
        except:
            errors['validate_errors'] = "Username or password invalid"
    errors['token_errors'] = '<br>'.join(form.csrf_token.errors)
    errors['username_errors'] = '<br>'.join(form.username.errors)
    errors['password_errors'] = '<br>'.join(form.password.errors)
    template = env.get_template('login.html')
    content = template.render(links=links, form=form, errors=errors)
    return response.html(content)
Beispiel #16
0
async def login(request):
    message = ''
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # for demonstration purpose only, you should use more robust method
        if username == 'admin' and get_hash(
                password) == processor.main_config['password']:
            # use User proxy in sanic_auth, this should be some ORM model
            # object in production, the default implementation of
            # auth.login_user expects User.id and User.name available
            user = User(id=1, name=username)
            auth.login_user(request, user)
            jinja.flash(request, f'User login {username}')
            return response.redirect('/control')
        if username or password:
            jinja.flash(request, 'invalid username or password')
            message = 'invalid username or password'
    return jinja.render('login.html',
                        request,
                        message=message,
                        main_process_name=main_process_name)
Beispiel #17
0
async def register(request):
    errors = {}
    form = RegistrationForm(request)
    if request.method == 'POST' and form.validate():
        username = form.username.data
        password = await crypto.hash_SHA512(form.password.data)
        # we need to create a new user
        try:
            user = await db_objects.create(Operator,
                                           username=username,
                                           password=password)
            login_user = User(id=user.id, name=user.username)
            auth.login_user(request, login_user)
            return response.redirect("/")
        except:
            # failed to insert into database
            errors['validate_errors'] = "failed to create user"
    errors['token_errors'] = '<br>'.join(form.csrf_token.errors)
    errors['username_errors'] = '<br>'.join(form.username.errors)
    errors['password_errors'] = '<br>'.join(form.password.errors)
    template = env.get_template('register.html')
    content = template.render(links=links, form=form, errors=errors)
    return response.html(content)
Beispiel #18
0
async def profile(request):
    id = request.json['_id']
    name = request.json['nickname']
    user = User(id=id, name=name)
    auth.login_user(request, user)
    return json_success(None)