Ejemplo n.º 1
0
def lookup():
    """
    This method validates the forms on the homepage,
    which can be found in forms.py, and then sends the
    result and user to another webpage.
    """
    form = LoginForm()
    if form.validate_on_submit():
        if set(form.artist.data).intersection("%^&*()<>?+=") or set(
                form.title.data).intersection("%^&*()<>?+="):
            flash('Whoops! Please omit special characters.', category='error')
            return render_template('whoops.html', title='error')
        artist = str(form.artist.data)
        artist = artist.replace('#', '')
        title = str(form.title.data)
        title = title.replace('#', '')
        return redirect('/recommendations/' + artist + '/' + title)
    if (form.artist.data and not form.title.data) or (not form.artist.data
                                                      and form.title.data):
        flash('Whoops! Please enter both the song name and artist.',
              category='error')
        return render_template('whoops.html', title='Input error')
    return render_template('lookup.html',
                           title='Smarter Music Recommendations',
                           form=form)
Ejemplo n.º 2
0
def login():
    if session.get('username'):
        return redirect(url_for('index'))

    form = LoginForm()

    if form.validate_on_submit() == True:
        email = form.email.data  #esse é o email submetido pelo usuario
        password = form.password.data  #esse é o password submetido pelo usuario

        user = Users.query.filter_by(email=email).first(
        )  #Essa query do SQL retorna o usuario filtrado por email

        if user and user.get_password(
                password):  #user é None se nao for encontrado, então é False.
            flash(f"{user.first_name}, You are successufully logged in",
                  "success")
            session["user_id"] = user.user_id
            session["username"] = user.first_name
            return redirect("/index")
        else:
            flash("Something went wrong. Try again", "danger")

    return render_template("login.html",
                           loginhl=True,
                           form=form,
                           title="Login")
Ejemplo n.º 3
0
def login1():
    form = LoginForm()

    if form.validate_on_submit():
        email = request.form.get("email")
        conn = sql.connect('database.db')
        qry_login = "******" + email + "'"
        loginData = conn.execute(qry_login)
        for rs in loginData:
            l_email_count = rs[0]
            l_email_name = rs[1]
            l_email_id = rs[2]
        if l_email_count == 0:
            flash("Sorry, something went wrong.", "danger")
        else:
            #flash("You are successfully logged in!" +l_email_name, "success")
            session['memid'] = l_email_id
            session['memname'] = l_email_name
            return redirect(url_for('index1'))

        conn.close
    return render_template("login1.html",
                           title="Login",
                           form=form,
                           login1=True)
Ejemplo n.º 4
0
def login():
    '''Login route'''

    if current_user.is_authenticated:
        return redirect(url_for('auth.profile'))

    form = LoginForm()
    if form.validate_on_submit():
        try:
            user = User.query.filter_by(email=form.email.data).first()
            if user and bcrypt.check_password_hash(user.password,
                                                   form.password.data):
                login_user(user)
                # next_page = request.args.get('next')
                # if next_page:
                #     return redirect(next_page)
                flash('Login successful!', 'success')
                return redirect(url_for('auth.profile'))
            else:
                flash('Login unsuccessful. Check email/password.',
                      'fail')
                return redirect(url_for('auth.login'))
        except Exception:
            flash('An error has occurred', 'fail')
            return redirect(url_for('auth.login'))
    return render_template('auth/login.html', form=form)
Ejemplo n.º 5
0
def login():

    if session.get('username'):
        redirect(url_for('index'))

    loginForm = LoginForm()
    if loginForm.validate_on_submit():
        with db.cursor() as cursor:
            password = loginForm.password.data
            cursor.execute(
                f'SELECT user.username, user.first_name, user.last_name, role.role_name, user.password FROM user, role WHERE user.role_id = role.role_id AND user.username = "******"'
            )
            auth = cursor.fetchone()
            cursor.close()
            if auth[0]:
                user = auth[0]
                if check_password_hash(user[4], password):
                    flash(f'Login request for user {loginForm.username.data}',
                          "success")
                    session['username'] = user[0]
                    session['name'] = f'{user[1]} {user[2]}'
                    session['role'] = user[3]
                    return redirect('/dashboard')
                else:
                    flash("Your password is wrong")
            else:
                flash("Sorry something went wrong", "danger")
    return render_template('login.html', form=loginForm)
Ejemplo n.º 6
0
def index():
    """Данная функция генерирует главную страницу для пользователя

    :return: Главная страница с чатами пользователя, является ли человек \
    в сессии, формой входа(Если человек не зарегистрирован, заголовок чата
    """
    find_chat_form = FindChatForm()
    chat_create_form = CreateChatForm()
    login_form = LoginForm()
    if login_form.validate_on_submit():
        User.login(login_form.login.data)
    if chat_create_form.validate_on_submit():
        name = chat_create_form.name.data
        code_type = chat_create_form.code_type.data
        code = chat_create_form.code.data
        access_key = chat_create_form.access_key.data
        if chat_create_form.is_file_valid():
            code = chat_create_form.file.data.read()
        chat_id = Chat.create(name, code, code_type, access_key)
        return redirect('/chat/' + str(chat_id))
    return render_template('index.html',
                           chats=Chat.find(find_chat_form.chat_title.data),
                           login_form=login_form,
                           chat_create_form=chat_create_form,
                           find_chat_form=find_chat_form,
                           login=User.get_login(),
                           allowed_ex=",".join([
                               '.' + i
                               for i in app.config["ALLOWED_EXTENSIONS"]
                           ]),
                           allowed_languages=app.config["ALLOWED_LANGUAGES"])
Ejemplo n.º 7
0
def login():
    if session.get("user"):
        return redirect(url_for("index"))

    loginForm = LoginForm()

    if request.method == "GET":
        return render_template("login.html", loginForm=loginForm)
    elif request.method == "POST":
        if loginForm.validate_on_submit():
            email = loginForm.email.data
            password = loginForm.password.data
            user = db.session.query(User).filter(User.email == email).first()
            if user and user.checkPassword(password):
                id = user.id
                firstName = user.firstName
                lastName = user.lastName
                session["user"] = {
                    "id": id,
                    "email": email,
                    "firstName": firstName,
                    "lastName": lastName
                }

                flash(f"{user.firstName}, you have successfully logged in",
                      "success")
                return redirect(url_for("index"))
            else:
                flash("Invalid username / password.", "danger")
        return render_template("login.html", loginForm=loginForm)
Ejemplo n.º 8
0
def get_login():
    form = LoginForm()
    if form.validate_on_submit():
        flash('Login requested for user {}, remember_me={}'.format(
            form.username.data, form.remember_me.data))
        return redirect('/index')
    return render_template("login.html", title="Sign in", form=form)
Ejemplo n.º 9
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('API'))
    form = LoginForm()
    if form.validate_on_submit():

        #assigning the values entered in the form to variables
        uname = form.username.data
        pas = form.password.data

        global a, usr, c
        c = Account.query.filter_by(username=uname).first()

        usr = uname

        #checking if the credentials entered are valid
        logn = Account.query.filter_by(username=uname, auth_id=pas).first()
        if logn is not None:
            flash('You have been logged in', 'success')
            login_user(c, remember=form.remember.data)
            return redirect(url_for('API'))

        else:
            abort(403)
        log = Account.query.filter_by(username=uname).first()

    return render_template('login.html', title='Login', form=form)
Ejemplo n.º 10
0
def login():

    form = LoginForm(request.form)

    # POST
    if request.method == "POST":

        if not form.validate():
            return render_template("login.html", form=form, message="Введены некорректные данные")

        login = form.login.data
        password = form.password.data
        remember_me = form.remember_me.data

        result = get_user_info(login, password)

        if result is not False and result is not None:
            session.permanent = remember_me
            session["login"] = login
            session["password"] = password
            return redirect("/")
        return render_template(
            "login.html", title="Вход", form=form, message="Вход не удался. Возможно введены неверные данные"
        )

    # GET
    if auth():
        return redirect("/")
    return render_template("login.html", title="Вход", form=form)
def login():
    # Check if user is already logged in
    if current_user.is_authenticated:
        return redirect(url_for('account'))
    form = LoginForm()
    # Check if a request is both a POST request and a valid request
    if form.validate_on_submit():
        email         = form.email.data
        password      = form.password.data   
        remember      = form.remember.data
        user          = User.objects(email = email).first()     
        
        # Check if user exist and verify password against DB
        if user and user.get_password(password):
            # Login user
            login_user(user, remember = remember)
            flash('You are succesfully logged in!', 'success')
            # Go to page user intented to visit before logging in
            next_page = request.args.get('next')
            if next_page:
                return redirect(next_page)
            else:
                return redirect(url_for('account'))
        else:
            flash('Login failed. Please make sure you use the correct username (= e-mail) and password!', 'danger')

    # Getting latest 5 recipes for footer
    footer_recipes = Recipe.objects[:5].order_by('-recipe_id')

    # Render html, giving its title, passing in the form and footer recipes
    return render_template('login.html', title = 'Login', form = form, footer_recipes = footer_recipes)
Ejemplo n.º 12
0
def home():
    if request.method == 'GET' and current_user.is_authenticated:
        if current_user.user_login_id == 'reception':
            return render_template('home.html', title="Home", reception=True)
        elif current_user.user_login_id == 'pharmacy':
            return render_template('home.html', title="Home", pharmacy=True)
        elif current_user.user_login_id == 'diagnosis':
            return render_template('home.html', title="Home", diagnostics=True)

    form = LoginForm()
    if form.validate_on_submit():
        username = request.form.get('username')
        password = request.form.get('password')
        user = User.query.filter_by(user_login_id=username).first()
        if user and sha256_crypt.verify(password, user.password):
            login_user(user, remember=True)
            if username == 'reception':
                flash('Welcome Receptionist', 'success')
                return render_template('home.html',
                                       title="Home",
                                       reception=True)
            elif username == 'pharmacy':
                flash('Welcome Pharmacist', 'success')
                return render_template('home.html',
                                       title="Home",
                                       pharmacy=True)
            elif username == 'diagnosis':
                flash('Welcome Diagnostician', 'success')
                return render_template('home.html',
                                       title="Home",
                                       diagnostics=True)

    flash('Please Enter Proper Credentials', 'danger')
    return redirect(url_for('login'))
Ejemplo n.º 13
0
def login():
    if current_user.is_authenticated:  # already logged in, redirect based on account type
        if current_user.access == "admin":
            return redirect('/admin')
        return redirect('/clubhouse')
    form = LoginForm()
    if form.validate_on_submit():
        # read user input to form
        username = request.form['user']
        password = request.form['password']
        u_id = get_id_from_username(username)
        if u_id:  # valid user
            user = User(u_id)  # generate user object
            if user.check_password(password):  # login success
                login_user(user, remember=form.remember.data)
                session['fresh'] = True  # manually set fresh session
                # determine whether this user prefers last, first or first last
                session['last_name_first'] = user.last_name_first
                # redirect based on user status
                if user.access == "admin":
                    # reset stored club id and impersonation name
                    if 'club_id' in session:
                        session.pop('club_id')
                    if 'impersonation' in session:
                        session.pop('impersonation')
                    return redirect('/admin')
                # otherwise this user is a clubhouse coordinator
                session['club_id'] = get_club_id_from_user(
                    user_id=u_id)  # store club id in use
                return redirect('/clubhouse')
        # display that credentials are incorrect
        flash(_l("Username/password combination incorrect."))
        return redirect('/login')
    return render_template('login.html', form=form, refresh=False)
Ejemplo n.º 14
0
def login():

    form = LoginForm(request.form)

    # POST
    if request.method == 'POST':

        if not form.validate():
            return render_template('login.html',
                                   form=form,
                                   message='Введены некорректные данные')

        login = form.login.data
        password = form.password.data
        remember_me = form.remember_me.data

        result = get_user_info(login, password)

        if result is not False and result is not None:
            session.permanent = remember_me
            session['login'] = login
            session['password'] = password
            return redirect('/')
        return render_template(
            'login.html',
            title="Вход",
            form=form,
            message='Вход не удался. Возможно введены неверные данные')

    # GET
    if auth():
        return redirect('/')
    return render_template('login.html', title="Вход", form=form)
Ejemplo n.º 15
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash('Loggin In')
        return redirect(url_for('index'))

    return render_template('login.html', title='Sign In', form=form)
Ejemplo n.º 16
0
def login():

    # Preventing logged in user from going to login route again
    if session.get('username'):
        return redirect(url_for('index'))

    form = LoginForm()

    # Validation
    if form.validate_on_submit():
        # email = request.form['email']
        # OR
        email = form.email.data
        password = form.password.data

        user = User.objects(email=email).first()

        # Checking if user is registered or not and if password matched or not
        if user and user.get_password(password):
            flash(f"{user.first_name} You are successfully logged in!",
                  "success")

            # Adding user details to session
            session['user_id'] = user.user_id
            session['username'] = user.first_name
            return redirect(url_for('index'))
        else:
            flash("You're not registered!", "danger")
    return render_template('login.html', title="Login", form=form, login=True)
Ejemplo n.º 17
0
def login():
    if 'user_id' in session:
        if session['user_type'] == 'E':
            return redirect(url_for('create_customer'))
        else:
            return redirect(url_for('account_details'))
    form = LoginForm()
    if form.validate_on_submit():
        sql = text(
            "SELECT user_type FROM userstore WHERE loginid = :x AND password = :y"
        )
        # print(form.login.data)
        # print(form.password.data)
        rslt = db.engine.execute(sql, x=form.login.data, y=form.password.data)
        user_type = [row[0] for row in rslt]
        # id = Userstore.query.filter(and_(Userstore.loginid == form.login.data,Userstore.
        # password==form.password.data)).first()
        form.login.data = ''
        # print(user_type)
        if len(user_type) == 0:
            flash('Entered Login ID or Password is Wrong !', 'danger')
        else:
            session['user_id'] = form.login.data
            session['user_type'] = user_type[0]
            if user_type[0] == 'E':
                return redirect(url_for('create_customer'))
            else:
                return redirect(url_for('account_query1'))
    return render_template('login.html', form=form, title='Login')
Ejemplo n.º 18
0
def index():             #index is the login page
    logged_in = False
    form      = LoginForm()  #form is an instance of the LoginForm class
    title     = "Login"

    if form.validate_on_submit():
        #get the email and password from the FORM
        email          =    form.email.data
        password       =    form.password.data

        #check if email and password from the FORM exist in the DATABASE
        #get the 1st user in the db with email matching the email entered in FORM
        userInDatabase = User.objects(email=email).first() 
        
        if userInDatabase:
            #the email entered in FORM does exist in DATABASE
            #now check if the corresponding passwords match
            if userInDatabase.compare_passwords(password):
                #passwords match
                flash(f"You are successfully logged in { userInDatabase.first_name }!", "success")

                return redirect("/home") #take legitimate user to the home page

            else:
                flash("Incorrect email or password", "danger")    

        else:
            flash("Incorrect email or password", "danger")

    return render_template("index.html", title=title, form=form, index=True, logged_in=logged_in)
Ejemplo n.º 19
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash('Login requested for user {}, remember_me={}'.format(
            form.username.data, form.remember_me.data))
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)
def login():
    if session.get('username') and session.get('usertype') == ("rde"):
        return redirect("/create_patient")
    elif session.get('username') and session.get('usertype') == "pha":
        return redirect("/patient_search")
    elif session.get('username') and session.get('usertype') == "dse":
        return redirect("/patient_search2")

    loginForm = LoginForm()
    title = "Login"
    if loginForm.validate_on_submit():
        username = loginForm.username.data
        password = loginForm.password.data
        cursor.execute(
            """SELECT (`type`) FROM `user_login` WHERE `username` LIKE '{}' AND `password` LIKE '{}'"""
            .format(username, password))
        dataset = cursor.fetchone()

        if cursor.rowcount > 0:
            flash("Logged in SuccessFully")
            session['username'] = username
            session['usertype'] = dataset[0]
            if dataset[0] == ("rde"):
                return redirect("/create_patient")
            elif dataset[0] == "pha":
                return redirect("/patient_search")
            else:
                return redirect("/patient_search2")
    return render_template("login.html", title=title, form=loginForm)
Ejemplo n.º 21
0
def login():
    if (session.get('email')):
        return redirect("/")

    form = LoginForm(
    )  # The forms are created in forms.py. Each form has an associated class

    if (
            form.validate_on_submit()
    ):  # This checks if the form is submitted and all the fields marked required are filled.

        user = login_details.query.filter_by(
            email=request.form.get('email')).first(
            )  # The database queries are using ORM called SQL Alchemy.
        password = user.password
        accesslevel = user.accesslevel
        actual = request.form.get('password')
        if (check_password_hash(password, actual)):
            session['email'] = request.form.get(
                "email"
            )  #Reading the form data, id is used to grab the required field
            session['accesslevel'] = int(accesslevel)
            return redirect("/")
        else:
            flash("Oops! Something is wrong", "danger")
    return render_template(
        "login.html", login=True, form=form
    )  #Returns while it renders the template HTML file, present in the templates folder
Ejemplo n.º 22
0
def index():
    """
    Generates the main page and the automatic form using a generic AppItem object

    :return: the template to be served to the client
    """

    params = {'title': 'Main'}
    app_item = AppItem()
    # crates a model class from the application item
    app_item_form = model_form(AppItem, db.session, base_class=Form, field_args=app_item.field_args)

    login_form = LoginForm(request.form)
    if helpers.validate_form_on_submit(login_form):
        user = login_form.get_user()
        login.login_user(user)
        params['retry_login'] = False

        # redirect to prevent form double submit
        return redirect(request.url)
    else:
        if login_form.errors:
            params['retry_login'] = True

    params['is_authenticated'] = login.current_user.is_authenticated()

    check_errors()

    return render_template('index.html',
                           params=params,
                           form=app_item_form(obj=app_item),
                           login_form=login_form,
                           app_config=ActiveConfig)
Ejemplo n.º 23
0
def login():
    login_form = LoginForm()
    context = {'login_form': login_form}
    if login_form.is_submitted():
        user_id = login_form.username.data
        password = login_form.password.data

        user_doc = get_user(user_id)
        if user_doc.to_dict() is not None:
            password_from_db = user_doc.to_dict()['password']

            if check_password_hash(password_from_db, password):
                user_name = user_doc.to_dict()['user']
                user_data = UserData(user_id, user_name, password)
                user = UserModel(user_data)
                login_user(user)
                if (not existKey(user_id)):
                    return redirect(url_for('auth.keygen'))
                return redirect(url_for('index'))
            else:
                flash('Contraseña invalida')
        else:
            flash('El nombre de usuario No existe Intente de nuevo')

    return render_template('login.html', **context)
Ejemplo n.º 24
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash("Yo {} essai de s'inscrire, je me souvien tu d'une âme ? {}".
              format(form.username.data, form.remember_me.data))
        return index()
    return render_template('login.html', title='Insciption', form=form)
Ejemplo n.º 25
0
def login():
    """
    User login page.

    GET: Serve Log-in page.
    POST: If form is valid and new user creation succeeds, redirect user to the logged-in homepage.
    """
    if current_user.is_authenticated:
        return redirect(url_for("index"))  # Bypass if user is logged in

    login_form = LoginForm()
    if request.method == "POST":
        if login_form.validate_on_submit():
            email = login_form.email.data
            password = login_form.password.data
            user = User.query.filter_by(
                email=email).first()  # Validate Login Attempt
            if user and user.check_password(password=password):
                login_user(user)
                user.last_login = datetime.now()
                db.session.commit()
                flash('Welcome Back ', user.name)
                return redirect(url_for("index"))

        flash("Invalid username/password combination")
        return redirect(url_for("login"))

    return render_template(
        "login.html",
        form=login_form,
        title="Log in.",
        body="Log in with your User account.",
    )
Ejemplo n.º 26
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        flash('Login requisitado para o usuário {}, rememberMe={}'.format(
            form.username.data, form.rememberMe.data))
        return redirect('index')
    return render_template('login.html', title='Login', form=form)
Ejemplo n.º 27
0
def login_route():
    '''Login registered users'''

    if current_user.is_authenticated:
        return redirect(url_for('forum.index_page'))

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password,
                                               form.password.data):
            view_count = int(request.cookies.get('view-count', 0))
            view_count += 1
            # user_agent = request.headers.get('User-Agent')
            # host = request.headers.get('Host')
            # referer = request.headers.get('Referer')
            login_user(user)
            next_page = request.args.get('next')
            if next_page:
                pass
            #     return redirect(next_page)
            return redirect(url_for('auth.profile', _external=True))
        else:
            logger.warn('Login failure!!!!', exc_info=True)
            flash('Login failed. Check your email/password.', 'fail')
    return render_template('auth/login.html', form=form)
Ejemplo n.º 28
0
def login():
    form = LoginForm()
    title = 'Login'
    if form.validate_on_submit():
        user = User(form.password.data, form.email.data)
        user.select_user(form.email.data)
        print(user.select_user(form.email.data))
        print('user is None?', user == None)
        print(user)
        password = query('password', 'clients',
                         f"email='{form.email.data}'")[0]
        if user is not None and bcrypt.check_password_hash(
                password, form.password.data):
            login_user(user, form.remember.data)
            print("current user self.getname '{}'".format(login_fresh()))
            flash("Login Sucessful!", 'success')
            next = request.args.get('next')
            print(next)
            if next is None or not next.startswith('/'):
                next = url_for('index')
            return redirect(next)
        else:
            flash("Login Unsucessful, Please check email and password",
                  'danger')

    return render_template('login.html', form=form, title=title)
Ejemplo n.º 29
0
def login_page():
    """User login page."""
    # Bypass Login screen if user is logged in
    if current_user.is_authenticated:
        return redirect(url_for('main_bp.chat'))
    login_form = LoginForm(request.form)
    # POST: Create user and redirect them to the app
    if request.method == 'POST':
        if login_form.validate():
            # Get Form Fields
            email = request.form.get('email')
            password = request.form.get('password')
            # Validate Login Attempt
            user = User.query.filter_by(email=email).first()
            if user:
                if user.check_password(password=password):
                    login_user(user)
                    next = request.args.get('next')
                    return redirect(next or url_for('main_bp.chat'))
        flash('Invalid username/password combination')
        return redirect(url_for('auth_bp.login_page'))
    # GET: Serve Log-in page
    return render_template('login.html',
                           form=LoginForm(),
                           title='NinerChat | Log in',
                           template='login-page',
                           body="Log in with your User account.")
Ejemplo n.º 30
0
def login():
    form = LoginForm()

    if request.method == 'GET':
        return render_template('login.html',
                               form=form,
                               variables=variables,
                               captcha=captcha.create())

    if form.validate_on_submit():
        username = request.form.get('username')
        password = request.form.get('password')
        captcha_hash = request.form.get('captcha-hash')
        captcha_text = request.form.get('captcha_text')
        redirect_url = request.args.get(variables['redirect_url_param_name'],
                                        default='/')
        if not captcha.verify(captcha_text, captcha_hash):
            flash('Captcha is not valid.', 'error')
            return redirect(
                f'{url_for("login")}?{variables["redirect_url_param_name"]}={redirect_url}'
            )
        user = User.get(username=username, password=password)
        if user:
            if login_user(user):
                return redirect(redirect_url)
        flash('Username or password is invalid.', 'error')
        return redirect(
            f'{url_for("login")}?{variables["redirect_url_param_name"]}={redirect_url}'
        )
Ejemplo n.º 31
0
def login():
    if 'user_id' in session:
        if session['user_type'] == 'E':
            return redirect(url_for('create_patient'))
        elif session['user_type'] == 'P':
            return redirect(url_for('pharmacist'))
        elif session['user_type'] == 'D':
            return redirect(url_for('diagnostics'))
    form = LoginForm()
    if form.validate_on_submit():
        sql = text(
            "SELECT user_type FROM userstore WHERE loginid = :x AND password = :y"
        )
        rslt = db.engine.execute(sql, x=form.login.data, y=form.password.data)
        user_type = [row[0] for row in rslt]
        form.login.data = ''
        if len(user_type) == 0:
            flash('Entered Login ID or Password is Wrong !', 'danger')
        else:
            session['user_id'] = form.login.data
            session['user_type'] = user_type[0]
            if user_type[0] == 'E':
                return redirect(url_for('create_patient'))
            elif user_type[0] == 'P':
                return redirect(url_for('pharmacist'))
            elif user_type[0] == 'D':
                return redirect(url_for('diagnostics'))
    return render_template('login.html', form=form, title='Login')
Ejemplo n.º 32
0
def login(request):
    announcements = Announcement.get_all_enabled_annoucements()
    if not settings.LOGIN_ENABLED:
        # login disabled
        if request.method == 'POST':
            return HttpResponseForbidden()
        else:
            return render_to_response('application/wait.html',
                                      { 'announcements': announcements })     

    error_messages = []
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            passwd = form.cleaned_data['password']

            national_id = form.cleaned_data['national_id']
            applicants = list(Applicant.objects.filter(national_id=national_id).all())
            if len(applicants)!=0:
                applicant = applicants[0]
            else:
                applicant = None

            if applicant!=None:
                if applicant.activation_required:
                    email = applicant.email
                    return render_to_response(
                        'application/registration/activation-required.html',
                        { 'email': email })
                elif (applicant.check_password(passwd) or
                      (settings.DEBUG and settings.FAKE_LOGIN) or
                      (settings.USE_ADDITIONAL_PASSWORD and
                       applicant.check_additional_password(passwd))):
                    # authenticated

                    if not applicant.has_logged_in:
                        applicant.has_logged_in = True
                        applicant.save()

                    request.session['applicant_id'] = applicant.id
                    
                    return redirect_to_applicant_first_page(applicant)
            
            from django.forms.util import ErrorList

            form._errors['password'] = ErrorList(['รหัสผ่านผิดพลาด'])
            error_messages.append('รหัสผ่านผิดพลาด')
    else:
        form = LoginForm()

    return render_to_response('application/start.html',
                              { 'form': form,
                                'submission_deadline_passed':
                                    submission_deadline_passed(),
                                'errors': error_messages,
                                'announcements': announcements })
Ejemplo n.º 33
0
def login():
    # Here we use a class of some kind to represent and validate our
    # client-side form data. For example, WTForms is a library that will
    # handle this for us, and we use a custom LoginForm to validate.
    form = LoginForm()
    if form.validate_on_submit():
        # Login and validate the user.
        # user should be an instance of your `User` class
        login_user(user)

        flash('Logged in successfully.')

        next = request.args.get('next')
        # next_is_valid should check if the user has valid
        # permission to access the `next` url
        if not next_is_valid(next):
            return abort(400)

        return redirect(next or flask.url_for('index'))
    return render_template('login.html', form1=form)
Ejemplo n.º 34
0
def login():
    # Here we use a class of some kind to represent and validate our
    # client-side form data. For example, WTForms is a library that will
    # handle this for us, and we use a custom LoginForm to validate.
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        # Login and validate the user.
        # user should be an instance of your `User` class
        user = load_user(form.username.data)
        if (user is not None):
            m = hashlib.md5()
            m.update('form.password.data')
            print m.hexdigest()
            if user.id == form.username.data and \
                            user.password == m.hexdigest():
                login_user(user)
                flash('Logged in successfully.')
                return redirect(url_for('index'))
            else:
                flash('Login or password are incorrect')
    return render_template('login.html', form=form)
Ejemplo n.º 35
0
def sign_in(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/dashboard')
    else:
        args = {}
        args.update(csrf(request))
        if request.method == 'POST':
            form = LoginForm(request.POST)
            if form.is_valid():
                user = authenticate(username=request.POST["username"], password=request.POST["password"])
                if user is not None:
                    if user.is_active:
                        login(request, user)
                        return HttpResponseRedirect('/dashboard')
                    else:
                        args['myErrors'] = "User Not Activated."
                else:
                    args['myErrors'] = "Username or passwords Don't match."
        else:
            form = LoginForm()

        args['form'] = form
        return render_to_response('signin.html', args, RequestContext(request))