简体   繁体   中英

login in Angular & nodeJs &postgreSQL

I am new in using angular and node.Js I have angular app which have component for sign in , and in backend I have server node.Js with postgreSQL , it has table "users" how I can make the user login and get tha data from server ? I mean when the user write the email and password and click on the button signin i need to load his data . what should I do in the backend? Any suggestions/help would be highly appreciated. Thanks

From the Angular app you can send a http post request to the backend server with the email id and password of the user. There you can get the user data from the database table with the matching email id and check the password. If the user exits and the password matches return success with the user data else return some other data like -1 to indicate it's unauthorized user.

You will need to follow some step to do this.

1) Create simple login form : ok you go it.

2) Send the user credential to the server. Here is a simple login service that you can use from your component

@Injectable()
export class LoginService {

  constructor(private http: HttpClient, private userStorage: UserStore) {
  } 

 async login(credential: { email: string, password: string }): Promise<boolean> {
    try {
      const token = await this.http.post('/auth/authenticate', credential, { responseType: 'text' })
        .pipe(share()).toPromise();
      this.userStorage.setToken(token);
      return true;
    } catch (err) {
      if (err.status !== HttpStatus.FORBIDDEN) {
        throw err;
      }
      return false;
    }
  }

Here you call your server in POST with the user information and this one give you a crypted token allowing you to access the API function depending on your privilege. The token generally look like :

Bearer eozaeza3e232az3eaze23zaeeo (standard auth token)

We keep this token in a "store" which can be localstore/cookie for exemple. You can create an angular service to handle this. Here I called him UserStore

3) On the server side you need now to valide the user crendentiel that you have receive in the "POST" request. So you simply make an sql request in your user database to see if you found him ( dont forget to crypt your password in database ). If you don't find him send a bad credential response.

4) When you have found the user you need to create a token. You can use https://github.com/auth0/node-jsonwebtoken to do this. A token is a simple crypted object representing the user information. Here is how you can create one :

const jwtToken = jwt.sign({
          email: account.email,
          givenName: account.givenName,
          role: account.role
        }, Config.get().AUTH_JWT_KEY, { expiresIn: 3600 });

The Config.get().AUTH_JWT_KEY is just a simple hashed string representing a "password" to crypt the token. The token should not be Uncrypted in the front side , keep this key on your back side.

5) The server give you a 200 and you have your token :). You can now use it to call the restricted endpoint of you API. To do this you will need to add this token in your request headers. In angular there is what we call an interceptor . It's a service that will be used to do some action when you send an http request or when you have a response. Thanks to him you will be able to add the token in every request.

You can find some code here : How to handle 401 unauthenticated error in Angular 6

6) You server will now need to read this token to know if your user can have access or not to some endpoint. He will need to "uncrypt" the token the user gave him thanks to the key "Config.get().AUTH_JWT_KEY". Using jsonwebtoken

const account = jwt.verify(token, Config.get().AUTH_JWT_KEY);

Here you have your account you can now check your user permission and see what he can do :D

7) Last small part. You will also need to "protect" your fronted to avoid people accessing page when they are not logged. You can check about the canActivate attribut on the angular router which use a guard . Here is an exemple

const appRouter: Routes = [
  { path: 'login', component: LoginPage },
  {
    path: 'app', component: AppPage, canActivate: [EnsureUserAuthGuard], resolve: { user: UserResolve },
    children: [
      { path: 'home', component: HomePage },
      { path: 'content', component: ContentPage }
    ]
  }]

To have access to my application (app) pages (home / content) you need to pass the EnsureUserAuthGuard. It a simple service that will check that the user have the token in the storage. If the user doesn't have the token he will be redirect to the login page

@Injectable()
export class EnsureUserAuthGuard implements CanActivate {

  constructor(private userStore: UserStore,
    private router: Router) {
  }

  canActivate() {
    if (!lodash.isEmpty(this.userStore.getToken())) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM