Login to Noah Grocery

Login Prompt

To let users sign in with a username and password, the app needs a page which prompts the user to enter their credentials. In this section, you’ll add a signin page.

Create a file that will contain authentication-related routes.

Add the following code to that file, which creates a route that will render the signin page.

var express = require('express'); var router = express.Router(); router.get('/login', function(req, res, next) < res.render('login'); >); module.exports = router; 

Next, add these routes to the app. Open app.js and require() the newly created auth routes at line 10, below require(‘./routes/index’) .

var indexRouter = require('./routes/index'); var authRouter = require('./routes/auth'); 

Continuing within app.js , use() the newly require() ‘d authRouter at line 27, below app.use(‘/’, indexRouter) .

app.use('/', indexRouter); app.use('/', authRouter); 

The signin page has been added to the app! See how it looks by starting the server.

Open http://localhost:3000 and click «Sign in.» You are prompted to sign in, but there’s no place to enter a username and password.

Add an HTML form which will allow the user to input their credentials. Open views/login.ejs and add a form at line 15, below the «Sign in» heading.

h1>Sign in h1> form action="/login/password" method="post"> section> label for="username">Username label> input id="username" name="username" type="text" autocomplete="username" required autofocus> section> section> label for="current-password">Password label> input id="current-password" name="password" type="password" autocomplete="current-password" required> section> button type="submit">Sign in button> form> 

Refresh the page. The app now has a signin page that prompts the user for their username and password. Next, you will verify the username and password.

Источник

Форма ввода логина и пароля на JavaScript

Здесь мы рассмотрим совсем не сложный скрипт, написанный на JavaScript, который создает форму ввода логина и пароля. Отличительной чертой данного скрипта является то, что в зависимости от введенного логина и пароля происходит перенаправление пользователя на заданную страничку или сайт.

Читайте также:  Yandex market class php

Для наглядного примера работы данного скрипта кликните по кнопке «Войти на сайт», находящейся чуть ниже. Если в поле «логин» ввести login, а в поле «пароль» pass, то Вас автоматически перебросит на главную страницу нашего сайта. А если в поле «логин» ввести login2, а в поле «пароль» pass2, то Вы уже окажетесь на нашем форуме.

Если вводить какие-либо другие значения в поля «логин» и «пароль», то Вам будет выдано сообщение Неверный логин или пароль! и Вы вернетесь обратно на эту же страничку.

Для получения такой формы ввода логина и пароля, как в примере выше, воспользуйтесь следующим JavaScript кодом, который необходимо будет поместить в начало Вашей странички:

< script type = "text/javascript" >
function Input () login_ok = false ;
user_name = «» ;
password = «» ;
user_name = prompt ( «Логин» , «» );
user_name = user_name . toLowerCase ();
password = prompt ( «Пароль» , «» );
password = password . toLowerCase ();
if ( user_name == «login» && password == «pass» ) login_ok = true ;
window . location = «index.php» ;
>
if ( user_name == «login2» && password == «pass2» ) login_ok = true ;
window . location = «forum/index.php» ;
>

if ( login_ok == false ) alert ( «Неверный логин или пароль!» );
>

Для вывода формы ввода логина и пароля нам понадобится кнопка, при нажатии на которую появится наша форма. Следовательно, нам необходимо добавить эту кнопку при помощи вот такого небольшого кода:

Если Вы все сделали правильно, то в результате у Вас должна получиться точно такая же формы ввода логина и пароля, как и в примере, показанном ранее.

Источник

JavaScript Login Username & Password

I am making a website for a school project, and in it, there is a login page. Right now, there is only 1 login username and password. How can I have TWO username and TWO passwords? I have tried the else if, but it didn’t work. Any ideas? The code for the login is below.
Thanks

      Home Contact Us! Products     
Login to Noah Grocery
Username: Password:

>Solution :

There are multiple ways to do this, as you are new and its a school project I just kept it simple.

I wrapped each user/pass in () and added || as or between the two groups and added them on separate lines to make it obvious.

function check(form) < if (form.userid.value == "admin" && form.pwd.value == "noahgrocery")< form.action = "#"; return true; >else if(form.userid.value == "admin2" && form.pwd.value == "noahgrocery2") < form.action = "#"; return true; >else < alert("Incorrect Password or Username") return false; >>
Home Contact Us! Products     
Login to Noah Grocery
Username: Password:

Источник

Username & Password

A username and password is the traditional, and still most widely used, way for users to authenticate to a website. Support for this mechanism is provided by the passport-local package.

Install

To install passport-local , execute the following command:

$ npm install passport-local 

Configure

The following code is an example that configures and registers the LocalStrategy :

var passport = require('passport'); var LocalStrategy = require('passport-local'); var crypto = require('crypto'); passport.use(new LocalStrategy(function verify(username, password, cb) < db.get('SELECT * FROM users WHERE username = ?', [ username ], function(err, user) < if (err) < return cb(err); > if (!user) < return cb(null, false, < message: 'Incorrect username or password.' >); > crypto.pbkdf2(password, user.salt, 310000, 32, 'sha256', function(err, hashedPassword) < if (err) < return cb(err); > if (!crypto.timingSafeEqual(user.hashed_password, hashedPassword)) < return cb(null, false, < message: 'Incorrect username or password.' >); > return cb(null, user); >); >); >); 

The LocalStrategy constructor takes a verify function as an argument, which accepts username and password as arguments. When authenticating a request, the strategy parses a username and password, which are submitted via an HTML form to the web application. The strategy then calls the verify function with those credentials.

The verify function is responsible for determining the user to which the username belongs, as well as verifying the password. Because the verify function is supplied by the application, the application is free to use a database and schema of its choosing. The example above illustrates usage of a SQL database.

Similarly, the application is free to determine its password storage format. The example above illustrates usage of PBKDF2 when comparing the user-supplied password with the hashed password stored in the database.

In case of authentication failure, the verify callback supplies a message, via the message option, describing why authentication failed. This will be displayed to the user when they are re-prompted to sign in, informing them of what went wrong.

Prompt

The user is prompted to sign in with their username and password by rendering a form. This is accomplished by defining a route:

app.get('/login', function(req, res, next) < res.render('login'); >); 

The following form is an example which uses best practices:

form action="/login/password" method="post"> div> label for="username">Username label> input id="username" name="username" type="text" autocomplete="username" required /> div> div> label for="current-password">Password label> input id="current-password" name="password" type="password" autocomplete="current-password" required /> div> div> button type="submit">Sign in button> div> form> 

Authenticate

When the user submits the form, it is processed by a route that authenticates the user using the username and password they entered.

app.post('/login/password', passport.authenticate('local', < failureRedirect: '/login', failureMessage: true >), function(req, res) < res.redirect('/~' + req.user.username); >); 

If authentication succeeds, passport.authenticate() middleware calls the next function in the stack. In this example, the function is redirecting the authenticated user to their profile page.

When authentication fails, the user is re-prompted to sign in and informed that their initial attempt was not successful. This is accomplished by using the failureRedirect option, which will redirect the user to the login page, along with the failureMessage option which will add the message to req.session.messages .

Источник

Оцените статью