2016-03-14 20:20:29 +08:00
|
|
|
///<reference path="../../browser.d.ts"/>
|
2016-03-13 18:28:29 +08:00
|
|
|
|
|
|
|
import {Injectable} from 'angular2/core';
|
|
|
|
import {User} from "../../../common/entities/User";
|
|
|
|
import {Event} from "../../../common/event/Event";
|
2016-03-19 16:58:27 +08:00
|
|
|
import {UserService} from "./user.service";
|
|
|
|
import {LoginCredential} from "../../../common/entities/LoginCredential";
|
|
|
|
import {Message} from "../../../common/entities/Message";
|
2016-03-21 03:06:14 +08:00
|
|
|
import { Cookie } from 'ng2-cookies/ng2-cookies';
|
2016-03-13 18:28:29 +08:00
|
|
|
|
2016-04-10 00:06:29 +08:00
|
|
|
declare module ServerInject{
|
|
|
|
export var user;
|
|
|
|
}
|
|
|
|
|
2016-03-13 18:28:29 +08:00
|
|
|
@Injectable()
|
|
|
|
export class AuthenticationService{
|
|
|
|
|
2016-03-19 16:58:27 +08:00
|
|
|
private _user:User = null;
|
2016-03-13 18:28:29 +08:00
|
|
|
public OnAuthenticated:Event<User>;
|
|
|
|
|
2016-03-19 16:58:27 +08:00
|
|
|
constructor(private _userService: UserService){
|
2016-03-13 18:28:29 +08:00
|
|
|
this.OnAuthenticated = new Event();
|
2016-03-21 03:06:14 +08:00
|
|
|
|
|
|
|
//picking up session..
|
|
|
|
if(this.isAuthenticated() == false && Cookie.getCookie('pigallery2-session') != null){
|
2016-04-10 00:06:29 +08:00
|
|
|
if(typeof ServerInject !== "undefined" && typeof ServerInject.user !== "undefined"){
|
|
|
|
console.log("user found");
|
|
|
|
this.setUser(ServerInject.user);
|
|
|
|
}
|
2016-03-21 03:06:14 +08:00
|
|
|
this.getSessionUser();
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
private getSessionUser(){
|
2016-04-10 00:06:29 +08:00
|
|
|
this._userService.getSessionUser().then( (message:Message<User>) =>{
|
2016-03-26 18:19:10 +08:00
|
|
|
if(message.error){
|
|
|
|
console.log(message.error);
|
2016-03-21 03:06:14 +08:00
|
|
|
}else{
|
|
|
|
this._user = message.result;
|
|
|
|
this.OnAuthenticated.trigger(this._user);
|
|
|
|
}
|
|
|
|
});
|
2016-03-13 18:28:29 +08:00
|
|
|
}
|
|
|
|
|
2016-03-19 16:58:27 +08:00
|
|
|
public login(credential:LoginCredential){
|
|
|
|
this._userService.login(credential).then( (message:Message<User>) =>{
|
2016-03-26 18:19:10 +08:00
|
|
|
if(message.error){
|
|
|
|
console.log(message.error);
|
2016-03-19 16:58:27 +08:00
|
|
|
}else{
|
2016-04-10 00:06:29 +08:00
|
|
|
this.setUser(message.result);
|
2016-03-19 16:58:27 +08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2016-04-10 00:06:29 +08:00
|
|
|
|
|
|
|
private setUser(user:User){
|
|
|
|
this._user = user;
|
|
|
|
this.OnAuthenticated.trigger(this._user);
|
|
|
|
}
|
2016-03-13 18:28:29 +08:00
|
|
|
|
2016-03-19 16:58:27 +08:00
|
|
|
public isAuthenticated():boolean{
|
2016-03-21 03:06:14 +08:00
|
|
|
return (this._user && this._user != null) ? true : false;
|
2016-03-13 18:28:29 +08:00
|
|
|
}
|
2016-03-19 16:58:27 +08:00
|
|
|
|
2016-03-13 18:28:29 +08:00
|
|
|
|
|
|
|
|
|
|
|
}
|