refactoring

This commit is contained in:
병준 박 2022-08-08 07:51:08 +00:00
parent 080e597a76
commit f310e5b15c
12 changed files with 97 additions and 104 deletions

11
package-lock.json generated
View File

@ -26,6 +26,7 @@
"crypto-js": "3.3.0", "crypto-js": "3.3.0",
"google-protobuf": "^3.20.1", "google-protobuf": "^3.20.1",
"highlight.js": "11.4.0", "highlight.js": "11.4.0",
"js-base64": "^3.7.2",
"lodash-es": "4.17.21", "lodash-es": "4.17.21",
"moment": "^2.29.4", "moment": "^2.29.4",
"nats.ws": "^1.8.1", "nats.ws": "^1.8.1",
@ -9311,6 +9312,11 @@
"url": "https://github.com/chalk/supports-color?sponsor=1" "url": "https://github.com/chalk/supports-color?sponsor=1"
} }
}, },
"node_modules/js-base64": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.7.2.tgz",
"integrity": "sha512-NnRs6dsyqUXejqk/yv2aiXlAvOs56sLkX6nUdeaNezI5LFFLlsZjOThmwnrcwh5ZZRwZlCMnVAY3CvhIhoVEKQ=="
},
"node_modules/js-tokens": { "node_modules/js-tokens": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@ -21775,6 +21781,11 @@
} }
} }
}, },
"js-base64": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.7.2.tgz",
"integrity": "sha512-NnRs6dsyqUXejqk/yv2aiXlAvOs56sLkX6nUdeaNezI5LFFLlsZjOThmwnrcwh5ZZRwZlCMnVAY3CvhIhoVEKQ=="
},
"js-tokens": { "js-tokens": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",

View File

@ -31,6 +31,7 @@
"crypto-js": "3.3.0", "crypto-js": "3.3.0",
"google-protobuf": "^3.20.1", "google-protobuf": "^3.20.1",
"highlight.js": "11.4.0", "highlight.js": "11.4.0",
"js-base64": "^3.7.2",
"lodash-es": "4.17.21", "lodash-es": "4.17.21",
"moment": "^2.29.4", "moment": "^2.29.4",
"nats.ws": "^1.8.1", "nats.ws": "^1.8.1",

View File

@ -2,7 +2,8 @@ import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { catchError, Observable, of, switchMap, throwError } from 'rxjs'; import { catchError, Observable, of, switchMap, throwError } from 'rxjs';
import { AuthUtils } from 'app/core/auth/auth.utils'; import { AuthUtils } from 'app/core/auth/auth.utils';
import { UserService } from 'app/core/user/user.service'; import { WebSessionStorageService } from 'app/core/web-storage/services/web-session-storage.service';
import { IdentityService } from 'app/modules/polyglot/member/services/identity.service';
@Injectable() @Injectable()
export class AuthService { export class AuthService {
@ -13,7 +14,8 @@ export class AuthService {
*/ */
constructor( constructor(
private _httpClient: HttpClient, private _httpClient: HttpClient,
private _userService: UserService private _identityService: IdentityService,
private __webSessionStorageService: WebSessionStorageService
) {} ) {}
// ----------------------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------------------
@ -58,27 +60,43 @@ export class AuthService {
* *
* @param credentials * @param credentials
*/ */
signIn(credentials: { email: string; password: string }): Observable<any> { signIn(
securityCodeHash: string,
credentials: {
email: string;
password: string;
captchaSecurityCode: string;
}
): Promise<any> {
return new Promise<void>((resolve, reject) => {
// Throw error, if the user is already logged in // Throw error, if the user is already logged in
if (this._authenticated) { if (this._authenticated) {
return throwError('User is already logged in.'); return reject('User is already logged in.');
} }
return this._httpClient.post('api/auth/sign-in', credentials).pipe( this._identityService
switchMap((response: any) => { .signin(
securityCodeHash,
credentials.captchaSecurityCode,
credentials.email,
credentials.password
)
.then((res) => {
this.__webSessionStorageService.set(
'accessToken',
res.getAccessToken()
);
// Store the access token in the local storage // Store the access token in the local storage
this.accessToken = response.accessToken; this.accessToken = res.getAccessToken();
// Set the authenticated flag to true // Set the authenticated flag to true
this._authenticated = true; this._authenticated = true;
// Store the user on the user service
this._userService.user = response.user;
// Return a new observable with the response
return of(response);
}) })
); .catch((e) => {
reject(e);
});
});
} }
/** /**
@ -102,9 +120,6 @@ export class AuthService {
// Set the authenticated flag to true // Set the authenticated flag to true
this._authenticated = true; this._authenticated = true;
// Store the user on the user service
this._userService.user = response.user;
// Return true // Return true
return of(true); return of(true);
}) })
@ -171,6 +186,7 @@ export class AuthService {
} }
// If the access token exists and it didn't expire, sign in using it // If the access token exists and it didn't expire, sign in using it
return this.signInUsingToken(); // return this.signInUsingToken();
return of(true);
} }
} }

View File

@ -3,6 +3,7 @@ import { DOCUMENT } from '@angular/common';
import * as jspb from 'google-protobuf'; import * as jspb from 'google-protobuf';
import * as nats from 'nats.ws'; import * as nats from 'nats.ws';
import { Base64 } from 'js-base64';
import { HEADER_CLIENT } from 'app/modules/protobuf/c2se/core/network_pb'; import { HEADER_CLIENT } from 'app/modules/protobuf/c2se/core/network_pb';
import { Client } from 'app/modules/protobuf/models/core/network_pb'; import { Client } from 'app/modules/protobuf/models/core/network_pb';
@ -59,7 +60,7 @@ export class NatsService {
this.__conn = conn; this.__conn = conn;
this.__webSessionStorageService this.__webSessionStorageService
.watch('SESSION_ID') .watch('accessToken')
.subscribe((sessionId) => { .subscribe((sessionId) => {
console.log('sessionId in NatsService', sessionId); console.log('sessionId in NatsService', sessionId);
}); });
@ -81,7 +82,7 @@ export class NatsService {
return new Promise<R>((resolve, reject) => { return new Promise<R>((resolve, reject) => {
let c = new Client(); let c = new Client();
c.setClientIp(this.__conn?.info?.client_ip + ''); c.setClientIp(this.__conn?.info?.client_ip + '');
c.setSessionId(this.__webSessionStorageService.get('SESSION_ID')); c.setAccessToken(this.__webSessionStorageService.get('accessToken'));
c.setSiteUrl(this.__document.location.hostname); c.setSiteUrl(this.__document.location.hostname);
let _opts: nats.RequestOptions = !!opts ? opts : { timeout: 3000 }; let _opts: nats.RequestOptions = !!opts ? opts : { timeout: 3000 };
@ -89,10 +90,9 @@ export class NatsService {
_opts.headers = nats.headers(); _opts.headers = nats.headers();
} }
var decoder = new TextDecoder('utf8');
_opts.headers.append( _opts.headers.append(
HEADER_CLIENT, HEADER_CLIENT,
btoa(decoder.decode(c.serializeBinary())) Base64.fromUint8Array(c.serializeBinary())
); );
this.__conn?.request(subject, req, _opts).then((msg) => { this.__conn?.request(subject, req, _opts).then((msg) => {

View File

@ -5,8 +5,6 @@ import { ActivatedRoute, Router } from '@angular/router';
import { fuseAnimations } from '@fuse/animations'; import { fuseAnimations } from '@fuse/animations';
import { FuseAlertType } from '@fuse/components/alert'; import { FuseAlertType } from '@fuse/components/alert';
import { AuthService } from 'app/core/auth/auth.service'; import { AuthService } from 'app/core/auth/auth.service';
import { WebSessionStorageService } from 'app/core/web-storage/services/web-session-storage.service';
import { IdentityService } from 'app/modules/polyglot/member/services/identity.service';
import { CaptchaResponse } from 'app/modules/protobuf/c2se/common/identity_pb'; import { CaptchaResponse } from 'app/modules/protobuf/c2se/common/identity_pb';
@Component({ @Component({
@ -36,8 +34,6 @@ export class AuthSignInComponent implements OnInit {
private _authService: AuthService, private _authService: AuthService,
private _formBuilder: FormBuilder, private _formBuilder: FormBuilder,
private _router: Router, private _router: Router,
private _identityService: IdentityService,
private __webSessionStorageService: WebSessionStorageService,
private _sanitizer: DomSanitizer private _sanitizer: DomSanitizer
) {} ) {}
@ -85,16 +81,17 @@ export class AuthSignInComponent implements OnInit {
// Hide the alert // Hide the alert
this.showAlert = false; this.showAlert = false;
this._identityService // Sign in
.signin( this._authService
.signIn(
this.captcha?.getSecurityCodeHash() as any, this.captcha?.getSecurityCodeHash() as any,
this.signInForm?.controls['captchaSecurityCode'].value, this.signInForm?.value
this.signInForm?.controls['email'].value,
this.signInForm?.controls['password'].value
) )
.then((res) => { .then(() => {
this.__webSessionStorageService.set('SESSION_ID', res.getSessionId()); // Set the redirect url.
// The '/signed-in-redirect' is a dummy url to catch the request and redirect the user
// to the correct page after a successful sign in. This way, that url can be set via
// routing file and we don't have to touch here.
const redirectURL = const redirectURL =
this._activatedRoute.snapshot.queryParamMap.get('redirectURL') || this._activatedRoute.snapshot.queryParamMap.get('redirectURL') ||
'/signed-in-redirect'; '/signed-in-redirect';
@ -118,37 +115,5 @@ export class AuthSignInComponent implements OnInit {
// Show the alert // Show the alert
this.showAlert = true; this.showAlert = true;
}); });
// Sign in
// this._authService.signIn(this.signInForm?.value).subscribe(
// () => {
// // Set the redirect url.
// // The '/signed-in-redirect' is a dummy url to catch the request and redirect the user
// // to the correct page after a successful sign in. This way, that url can be set via
// // routing file and we don't have to touch here.
// const redirectURL =
// this._activatedRoute.snapshot.queryParamMap.get('redirectURL') ||
// '/signed-in-redirect';
// // Navigate to the redirect url
// this._router.navigateByUrl(redirectURL);
// },
// (response) => {
// // Re-enable the form
// this.signInForm?.enable();
// // Reset the form
// this.signInNgForm?.resetForm();
// // Set the alert
// this.alert = {
// type: 'error',
// message: 'Wrong email or password',
// };
// // Show the alert
// this.showAlert = true;
// }
// );
} }
} }

View File

@ -50,7 +50,7 @@ export class IdentityService {
console.log('success', result, result.getDuplicated()); console.log('success', result, result.getDuplicated());
}) })
.catch((e: Error) => { .catch((e: Error) => {
console.log('failed', e.getCode(), e.getMessage(), e.getData()); console.log('failed', e);
reject(e); reject(e);
}); });
}); });
@ -70,7 +70,7 @@ export class IdentityService {
resolve(result); resolve(result);
}) })
.catch((e: Error) => { .catch((e: Error) => {
console.log('failed', e.getCode(), e.getMessage(), e.getData()); console.log('failed', e);
reject(e); reject(e);
}); });
}); });
@ -99,7 +99,7 @@ export class IdentityService {
resolve(result); resolve(result);
}) })
.catch((e: Error) => { .catch((e: Error) => {
console.log('failed', e.getCode(), e.getMessage(), e.getData()); console.log('failed', e);
reject(e); reject(e);
}); });
}); });

View File

@ -94,8 +94,8 @@ export namespace SigninResponse {
}; };
export class Result extends jspb.Message { export class Result extends jspb.Message {
getSessionId(): string; getAccessToken(): string;
setSessionId(value: string): void; setAccessToken(value: string): void;
serializeBinary(): Uint8Array; serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): Result.AsObject; toObject(includeInstance?: boolean): Result.AsObject;
@ -117,7 +117,7 @@ export namespace SigninResponse {
export namespace Result { export namespace Result {
export type AsObject = { export type AsObject = {
sessionId: string; accessToken: string;
}; };
} }
} }

View File

@ -537,7 +537,7 @@ if (jspb.Message.GENERATE_TO_OBJECT) {
function (includeInstance, msg) { function (includeInstance, msg) {
var f, var f,
obj = { obj = {
sessionId: jspb.Message.getFieldWithDefault(msg, 1, ""), accessToken: jspb.Message.getFieldWithDefault(msg, 1, ""),
}; };
if (includeInstance) { if (includeInstance) {
@ -580,7 +580,7 @@ proto.bet.beteran.c2se.backend.identity.SigninResponse.Result.deserializeBinaryF
switch (field) { switch (field) {
case 1: case 1:
var value = /** @type {string} */ (reader.readString()); var value = /** @type {string} */ (reader.readString());
msg.setSessionId(value); msg.setAccessToken(value);
break; break;
default: default:
reader.skipField(); reader.skipField();
@ -614,17 +614,17 @@ proto.bet.beteran.c2se.backend.identity.SigninResponse.Result.prototype.serializ
proto.bet.beteran.c2se.backend.identity.SigninResponse.Result.serializeBinaryToWriter = proto.bet.beteran.c2se.backend.identity.SigninResponse.Result.serializeBinaryToWriter =
function (message, writer) { function (message, writer) {
var f = undefined; var f = undefined;
f = message.getSessionId(); f = message.getAccessToken();
if (f.length > 0) { if (f.length > 0) {
writer.writeString(1, f); writer.writeString(1, f);
} }
}; };
/** /**
* optional string session_id = 1; * optional string access_token = 1;
* @return {string} * @return {string}
*/ */
proto.bet.beteran.c2se.backend.identity.SigninResponse.Result.prototype.getSessionId = proto.bet.beteran.c2se.backend.identity.SigninResponse.Result.prototype.getAccessToken =
function () { function () {
return /** @type {string} */ ( return /** @type {string} */ (
jspb.Message.getFieldWithDefault(this, 1, "") jspb.Message.getFieldWithDefault(this, 1, "")
@ -635,7 +635,7 @@ proto.bet.beteran.c2se.backend.identity.SigninResponse.Result.prototype.getSessi
* @param {string} value * @param {string} value
* @return {!proto.bet.beteran.c2se.backend.identity.SigninResponse.Result} returns this * @return {!proto.bet.beteran.c2se.backend.identity.SigninResponse.Result} returns this
*/ */
proto.bet.beteran.c2se.backend.identity.SigninResponse.Result.prototype.setSessionId = proto.bet.beteran.c2se.backend.identity.SigninResponse.Result.prototype.setAccessToken =
function (value) { function (value) {
return jspb.Message.setProto3StringField(this, 1, value); return jspb.Message.setProto3StringField(this, 1, value);
}; };

View File

@ -94,8 +94,8 @@ export namespace SigninResponse {
}; };
export class Result extends jspb.Message { export class Result extends jspb.Message {
getSessionId(): string; getAccessToken(): string;
setSessionId(value: string): void; setAccessToken(value: string): void;
serializeBinary(): Uint8Array; serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): Result.AsObject; toObject(includeInstance?: boolean): Result.AsObject;
@ -117,7 +117,7 @@ export namespace SigninResponse {
export namespace Result { export namespace Result {
export type AsObject = { export type AsObject = {
sessionId: string; accessToken: string;
}; };
} }
} }

View File

@ -537,7 +537,7 @@ if (jspb.Message.GENERATE_TO_OBJECT) {
function (includeInstance, msg) { function (includeInstance, msg) {
var f, var f,
obj = { obj = {
sessionId: jspb.Message.getFieldWithDefault(msg, 1, ""), accessToken: jspb.Message.getFieldWithDefault(msg, 1, ""),
}; };
if (includeInstance) { if (includeInstance) {
@ -580,7 +580,7 @@ proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result.deserializeBinary
switch (field) { switch (field) {
case 1: case 1:
var value = /** @type {string} */ (reader.readString()); var value = /** @type {string} */ (reader.readString());
msg.setSessionId(value); msg.setAccessToken(value);
break; break;
default: default:
reader.skipField(); reader.skipField();
@ -614,17 +614,17 @@ proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result.prototype.seriali
proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result.serializeBinaryToWriter = proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result.serializeBinaryToWriter =
function (message, writer) { function (message, writer) {
var f = undefined; var f = undefined;
f = message.getSessionId(); f = message.getAccessToken();
if (f.length > 0) { if (f.length > 0) {
writer.writeString(1, f); writer.writeString(1, f);
} }
}; };
/** /**
* optional string session_id = 1; * optional string access_token = 1;
* @return {string} * @return {string}
*/ */
proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result.prototype.getSessionId = proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result.prototype.getAccessToken =
function () { function () {
return /** @type {string} */ ( return /** @type {string} */ (
jspb.Message.getFieldWithDefault(this, 1, "") jspb.Message.getFieldWithDefault(this, 1, "")
@ -635,7 +635,7 @@ proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result.prototype.getSess
* @param {string} value * @param {string} value
* @return {!proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result} returns this * @return {!proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result} returns this
*/ */
proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result.prototype.setSessionId = proto.bet.beteran.c2se.frontend.identity.SigninResponse.Result.prototype.setAccessToken =
function (value) { function (value) {
return jspb.Message.setProto3StringField(this, 1, value); return jspb.Message.setProto3StringField(this, 1, value);
}; };

View File

@ -12,10 +12,10 @@ export class Client extends jspb.Message {
getSiteUrl(): string; getSiteUrl(): string;
setSiteUrl(value: string): void; setSiteUrl(value: string): void;
hasSessionId(): boolean; hasAccessToken(): boolean;
clearSessionId(): void; clearAccessToken(): void;
getSessionId(): string; getAccessToken(): string;
setSessionId(value: string): void; setAccessToken(value: string): void;
serializeBinary(): Uint8Array; serializeBinary(): Uint8Array;
toObject(includeInstance?: boolean): Client.AsObject; toObject(includeInstance?: boolean): Client.AsObject;
@ -39,6 +39,6 @@ export namespace Client {
export type AsObject = { export type AsObject = {
clientIp: string; clientIp: string;
siteUrl: string; siteUrl: string;
sessionId: string; accessToken: string;
}; };
} }

View File

@ -80,7 +80,7 @@ if (jspb.Message.GENERATE_TO_OBJECT) {
obj = { obj = {
clientIp: jspb.Message.getFieldWithDefault(msg, 1, ""), clientIp: jspb.Message.getFieldWithDefault(msg, 1, ""),
siteUrl: jspb.Message.getFieldWithDefault(msg, 2, ""), siteUrl: jspb.Message.getFieldWithDefault(msg, 2, ""),
sessionId: jspb.Message.getFieldWithDefault(msg, 3, ""), accessToken: jspb.Message.getFieldWithDefault(msg, 3, ""),
}; };
if (includeInstance) { if (includeInstance) {
@ -131,7 +131,7 @@ proto.bet.beteran.core.network.Client.deserializeBinaryFromReader = function (
break; break;
case 3: case 3:
var value = /** @type {string} */ (reader.readString()); var value = /** @type {string} */ (reader.readString());
msg.setSessionId(value); msg.setAccessToken(value);
break; break;
default: default:
reader.skipField(); reader.skipField();
@ -226,10 +226,10 @@ proto.bet.beteran.core.network.Client.prototype.hasSiteUrl = function () {
}; };
/** /**
* optional string session_id = 3; * optional string access_token = 3;
* @return {string} * @return {string}
*/ */
proto.bet.beteran.core.network.Client.prototype.getSessionId = function () { proto.bet.beteran.core.network.Client.prototype.getAccessToken = function () {
return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, ""));
}; };
@ -237,7 +237,7 @@ proto.bet.beteran.core.network.Client.prototype.getSessionId = function () {
* @param {string} value * @param {string} value
* @return {!proto.bet.beteran.core.network.Client} returns this * @return {!proto.bet.beteran.core.network.Client} returns this
*/ */
proto.bet.beteran.core.network.Client.prototype.setSessionId = function ( proto.bet.beteran.core.network.Client.prototype.setAccessToken = function (
value value
) { ) {
return jspb.Message.setField(this, 3, value); return jspb.Message.setField(this, 3, value);
@ -247,7 +247,7 @@ proto.bet.beteran.core.network.Client.prototype.setSessionId = function (
* Clears the field making it undefined. * Clears the field making it undefined.
* @return {!proto.bet.beteran.core.network.Client} returns this * @return {!proto.bet.beteran.core.network.Client} returns this
*/ */
proto.bet.beteran.core.network.Client.prototype.clearSessionId = function () { proto.bet.beteran.core.network.Client.prototype.clearAccessToken = function () {
return jspb.Message.setField(this, 3, undefined); return jspb.Message.setField(this, 3, undefined);
}; };
@ -255,7 +255,7 @@ proto.bet.beteran.core.network.Client.prototype.clearSessionId = function () {
* Returns whether this field is set. * Returns whether this field is set.
* @return {boolean} * @return {boolean}
*/ */
proto.bet.beteran.core.network.Client.prototype.hasSessionId = function () { proto.bet.beteran.core.network.Client.prototype.hasAccessToken = function () {
return jspb.Message.getField(this, 3) != null; return jspb.Message.getField(this, 3) != null;
}; };