Skip to content

Commit

Permalink
Added functionality for save user and added "authorization" header
Browse files Browse the repository at this point in the history
  • Loading branch information
AKosmachyov committed May 23, 2017
1 parent d2d7425 commit f9f7533
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 47 deletions.
1 change: 1 addition & 0 deletions app/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export class User {
login: string;
password: string;
name: string;
token: string;
}
37 changes: 30 additions & 7 deletions app/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Http, Headers } from '@angular/http';

import 'rxjs/add/operator/toPromise';

Expand All @@ -9,7 +9,9 @@ import { User } from '../models/user';
export class AuthService {
currentUser: User;
redirectUrl: string = '/dashboard';
constructor ( private http: Http ) {}
constructor ( private http: Http ) {
this.currentUser = this.restoreCredentialFromLS();
}

login (login: string, password: string): Promise<User> {
let user = {
Expand All @@ -19,12 +21,9 @@ export class AuthService {
return this.http.post('api/profile/login', user)
.toPromise()
.then(response => {
//TODO login
let body = response.json();
let newUser = new User();
newUser.name = body.name;
newUser._id = body._id;
return this.currentUser = newUser;
this.setCredentialForLS(body);
return this.currentUser = body as User;
});
}
checkin (user: User): Promise<User> {
Expand All @@ -34,10 +33,34 @@ export class AuthService {
user.password = null;
user.login = null;
user._id = response.json()._id;
user.token = response.json().token;
this.setCredentialForLS(user);
return this.currentUser = user;
});
}
logout (): void {
this.currentUser = undefined;
window.localStorage.clear();
}
getAuthorizationHeader () {
if (this.currentUser && this.currentUser.token)
return new Headers({ 'Authorization': `Basic ${this.currentUser.token}`});
return null;
}
setCredentialForLS(user: User) {
let ls = window.localStorage;
ls.setItem("token", user.token);
ls.setItem("name", user.name);
ls.setItem("_id", user._id);
}
restoreCredentialFromLS(): User {
let user: User = new User();
let ls = window.localStorage;
user.token = ls.getItem("token");
if(!user.token)
return null;
user._id = ls.getItem("_id");
user.name = ls.getItem("name");
return user;
}
}
18 changes: 11 additions & 7 deletions app/services/news-service.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,43 @@
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Http, Headers } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { News } from '../models/news';

import { AuthService } from './auth.service';

@Injectable()
export class NewsService {
private newsUrl = 'api/news';

constructor( private http: Http ) { }
constructor(
private http: Http,
private authService: AuthService
) { }

getNewsRange(from: number, to: number): Promise<News[]> {
return this.http.get(`api/news?from=${from}&to=${to}`)
return this.http.get(`api/news?from=${from}&to=${to}`, {headers: this.authService.getAuthorizationHeader()})
.toPromise()
.then(response => response.json() as News[])
.catch(this.handleError);
}
getNews(id: string): Promise<News> {
return this.http.get(`api/news/${id}`)
return this.http.get(`api/news/${id}`, {headers: this.authService.getAuthorizationHeader()})
.toPromise()
.then(response => response.json() as News)
.catch(this.handleError);
}
addNews(news: News): Promise<string> {
return this.http
.post('api/news/insert', news)
.post('api/news/insert', news, {headers: this.authService.getAuthorizationHeader()})
.toPromise()
.then(res => {
return res.text();
})
.catch(this.handleError);
}
update(news: News): Promise<string> {
return this.http.post(`api/news/${news._id}/modify`, news)
return this.http.post(`api/news/${news._id}/modify`, news, {headers: this.authService.getAuthorizationHeader()})
.toPromise()
.then((val) => val.text())
.catch(this.handleError)
Expand Down
59 changes: 34 additions & 25 deletions server/database.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,46 @@
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
const assert = require('assert');
const crypto = require('crypto');

const url = 'mongodb://localhost:27017/news-portal';

class DataBase {
constructor() {
MongoClient.connect(url, (err, db) => {
assert.equal(null, err);
if(err)
throw new Error("Can't connect to the database");
console.log("Connected successfully to db");
module.exports = db;
this.usersCollection = db.collection('Users');
this.newsCollection = db.collection('News');
});
}

logIn(user) {
return new Promise((resolve, reject) => {
this.usersCollection.findOne(user, (err, data) => {
if (err || !data) {
reject(err);
return;
}
resolve(data);
logInAsync(user) {
return this.usersCollection.findOne(user)
.then((user) => {
if (!user)
return Promise.reject("The user name and password don't match");
return user;
})
});
}

checkIn(user) {
return new Promise((resolve, reject) => {
this.usersCollection.findOne(user, (err, data) => {
if (err || data) {
reject(err);
return;
}
this.usersCollection.insertOne(user, (err, data) => {
if (err && data.insertedCount != 1) {
reject(err);
}
resolve(data);
});
})
checkInAsync(user) {
var self = this;
return self.usersCollection.findOne(user)
.then((data) => {
if (data)
return Promise.reject('This login is already registered');
return;
}).then(() => {
return self.generateTokenAsync();
}).then((token) => {
user.token = token;
return self.usersCollection.insertOne(user);
}).then((data) => {
if (data.insertedCount != 1)
Promise.reject('Error');
return (data.ops[0]);
});
}

Expand Down Expand Up @@ -85,6 +85,15 @@ class DataBase {
return;
})
}
generateTokenAsync() {
return new Promise(function (resolve, reject) {
crypto.randomBytes(64, (err, buf) => {
if (err)
reject(err);
resolve(buf.toString('hex'));
})
})
}
}


Expand Down
18 changes: 12 additions & 6 deletions server/routes/profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ router.post('/login', function(req, res, next) {
return;
}
req.body.login = req.body.login.toLowerCase();
dataBase.logIn(req.body).then((data)=>{

dataBase.logInAsync(req.body).then((user)=>{
res.json({
name: data.name,
_id: data._id
name: user.name,
_id: user._id,
token: user.token
});
}).catch((err)=> {
res.send("The user name and password don't match", 400);
Expand All @@ -23,10 +25,14 @@ router.post('/checkin', function(req, res, next) {
return;
}
req.body.login = req.body.login.toLowerCase();
dataBase.checkIn(req.body).then((data)=>{
res.json({_id: data._id});

dataBase.checkInAsync(req.body).then((user)=>{
res.json({
_id: user._id,
token: user.token
});
}).catch((err)=> {
res.send('This login is already registered.', 400);
res.send(err, 400);
});
});
function isValidUserCheckIn(user) {
Expand Down
5 changes: 3 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
{
"compilerOptions": {
"target": "es6",
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
"noImplicitAny": false,
"lib": ["es2015", "dom"]
}
}

0 comments on commit f9f7533

Please sign in to comment.