Browse Source

discord connect

master
gsd 1 month ago
parent
commit
b093266127
  1. 10
      src/app/app.component.html
  2. 10
      src/app/app.component.ts
  3. 8
      src/app/app.module.ts
  4. 13
      src/app/entities/DiscordAccount.ts
  5. 151
      src/app/pages/internal-components/dialogs/DiscordConnectDialog.ts
  6. 32
      src/app/services/auth.service.ts

10
src/app/app.component.html

@ -3,6 +3,11 @@
<span class="f13_color_primary lato" >факты</span><span class="f13_color_extra lato">13</span>
</div>
<span class="spacer"></span>
<button class="f13_color_primary"
[matMenuTriggerFor]="discordMenu"
mat-button
>Дискорд</button>
<button class="f13_color_primary"
style="margin-right: 5px"
*ngFor="let link of social_media_links"
@ -15,9 +20,12 @@
<button *ngIf="auth_service.steamdata?.nickname != null" mat-button mat-raised-button class="f13_color_primary" style="margin-right: calc((100% - 66%)/2)" [matMenuTriggerFor]="menu">
{{auth_service.steamdata?.nickname}}
</button>
<mat-menu #discordMenu>
<button mat-menu-item (click)="openDiscordConnect()">Привязать аккаунт</button>
<button mat-menu-item (click)="baseUtils.openUrlInNewWindow('/discord')">Перейти в Discord</button>
</mat-menu>
<mat-menu #menu="matMenu">
<button *ngIf="auth_service.steamIds != null && auth_service.steamIds.steam64 != null" mat-menu-item (click)="go2url(['profile', auth_service.steamIds.steam64])">Мой профиль</button>
<button mat-menu-item>Привязать дискорд</button>
<button mat-menu-item (click)="logout()">Выйти</button>
</mat-menu>
</mat-toolbar>

10
src/app/app.component.ts

@ -2,6 +2,8 @@ import { Component } from '@angular/core';
import {BaseUtils} from "./utils/BaseUtils";
import {Router} from "@angular/router";
import {AuthService} from "./services/auth.service";
import {MatDialog} from "@angular/material/dialog";
import {DiscordConnectDialog} from "./pages/internal-components/dialogs/DiscordConnectDialog";
@Component({
selector: 'app-root',
@ -11,7 +13,6 @@ import {AuthService} from "./services/auth.service";
export class AppComponent {
baseUtils: BaseUtils = new BaseUtils();
social_media_links: {link: string, name: string}[] = [
{name: "Дискорд", link: "discord"},
{name: "Телеграм", link: "https://t.me/facti13"},
{name: "Стим", link: "steam"}
]
@ -19,7 +20,8 @@ export class AppComponent {
logined: string | null = null;
constructor(private router: Router,
public auth_service: AuthService) {
public auth_service: AuthService,
private dialog: MatDialog) {
}
go2url(urls: string[], reopen: boolean = false) {
@ -37,5 +39,7 @@ export class AppComponent {
this.auth_service.login()
}
openDiscordConnect() {
this.dialog.open(DiscordConnectDialog)
}
}

8
src/app/app.module.ts

@ -57,6 +57,8 @@ import {FilterMatChipAdmins} from "./pages/internal-components/search-filters/ba
import {LivetimeServerMap} from "./pages/servers-page/livetime-server-map";
import {NewsViewDialog} from "./pages/main-page/NewsViewDialog";
import {AnnoncesListCarules} from "./pages/main-page/AnnoncesListCarules";
import {DiscordConnectDialog} from "./pages/internal-components/dialogs/DiscordConnectDialog";
import {MatStepperModule} from "@angular/material/stepper";
registerLocaleData(localeRu, "ru")
@ -87,7 +89,8 @@ registerLocaleData(localeRu, "ru")
FilterMatChipAdmins,
//dialogs
BanViewDialog,
NewsViewDialog
NewsViewDialog,
DiscordConnectDialog
],
imports: [
BrowserModule,
@ -117,7 +120,8 @@ registerLocaleData(localeRu, "ru")
MatDatepickerModule,
MatNativeDateModule,
MatProgressSpinnerModule,
MatDialogModule
MatDialogModule,
MatStepperModule
],
providers: [
{provide: LOCALE_ID, useValue: 'ru' },

13
src/app/entities/DiscordAccount.ts

@ -0,0 +1,13 @@
export class DiscordAccount {
accent_color!: number;
avatar!: string|null;
global_name!: string;
id!: string;
username!: string;
static fromData(data:any):DiscordAccount {
let d = new DiscordAccount();
Object.assign(d, data);
return d;
}
}

151
src/app/pages/internal-components/dialogs/DiscordConnectDialog.ts

@ -0,0 +1,151 @@
import {AfterViewInit, Component, Input} from "@angular/core";
import {AuthService} from "../../../services/auth.service";
import {ActionService} from "../../../services/action.service";
import {MatStepper} from "@angular/material/stepper";
import {DiscordAccount} from "../../../entities/DiscordAccount";
@Component({
selector: 'app-discord-connect-dialog',
template: `
<h1 mat-dialog-title style="color: black">Получение доступа к нашему серверу дискорда</h1>
<mat-dialog-content>
<app-need-auth-to-continue *ngIf="!authService.isAuth()"></app-need-auth-to-continue>
<div *ngIf="authService.isAuth()">
<mat-stepper orientation="vertical" [linear]="true" #stepper>
<mat-step>
<ng-template matStepLabel>Привязка к Steam</ng-template>
<ng-template matStepContent>
<div *ngIf="currentDiscordId==''">
<p>Проверка наличия привязки...</p>
</div>
<div *ngIf="currentDiscordId=='not_exists'">
<p>Твой аккаунт стима не привязан, можно приступить к следующему шагу</p>
<button mat-button matStepperNext>Далее</button>
</div>
<div *ngIf="currentDiscordId!='not_exists' && currentDiscordId!=''">
<p>У тебя на аккаунте уже есть привязанный дискорд, если хочешь его отвязать или потерял доступ, то жми скорее далее</p>
<button mat-button matStepperNext>Далее</button>
</div>
</ng-template>
</mat-step>
<mat-step *ngIf="currentDiscordId!=''">
<ng-template matStepLabel>Привязка к Discord</ng-template>
<ng-template matStepContent>
<div *ngIf="currentDiscordId=='not_exists'">
<p>Твой аккаунт стима не привязан, можно приступить к следующему шагу</p>
<button mat-button matStepperNext>Далее</button>
</div>
<div *ngIf="currentDiscordId!='not_exists' && currentDiscordId!=''">
<p>Удалить твой текущую связку?</p>
<p *ngIf="removeDiscordId == -1" style="color: red">Во время удаления связки аккаунтов произошла ошибка. Напиши админам в дискорде. Возможно ты еблан или мы.</p>
<button mat-button (click)="removeCurrentDiscordId()">Удалить</button>
</div>
</ng-template>
</mat-step>
<mat-step *ngIf="currentDiscordId!='' && currentDiscordId=='not_exists'">
<ng-template matStepLabel>Авторизация в дискорд</ng-template>
<ng-template matStepContent>
<div *ngIf="currentDiscordData == null">
<div *ngIf="currentDiscordDataStatus == 401">
<p>Нужно авторизоваться в дискорде для получения твоего уникального индификатора. Авторизуйся затем вернись в это окно так-же как и пришел!</p>
<button mat-button (click)="authService.discordLogin()">Авторизоваться</button>
</div>
<div *ngIf="currentDiscordDataStatus != 200 && currentDiscordDataStatus != 401">
<p>Сервер не может соединиться с дискордом для верификации данных, попробуй сделать это позже</p>
</div>
</div>
<div *ngIf="currentDiscordData != null && currentDiscordId=='not_exists'">
<p>Аккаунт стим {{authService.steamdata?.nickname}} будет привязан к аккаунту дискорд {{currentDiscordData.username}}</p>
<div [ngSwitch]="registerDiscordStatus" *ngIf="registerDiscordStatus!=null">
<p *ngSwitchCase="200" style="color: green">Аккаунты связаны, теперь можешь смотреть наш сервер дискорда</p>
<p *ngSwitchCase="413" style="color: red">Найден иной неотвязанный от текущего дискорда профиль стима. Если ты терял доступ к аккаунту то напиши админам в дискорде, мы отвяжем старые аккаунты.</p>
<p *ngSwitchCase="409" style="color: red">Найден иной неотвязанный от текущего профиля стима дискорд. Если ты терял доступ к аккаунту то напиши админам в дискорде, мы отвяжем старые аккаунты.</p>
<p *ngSwitchDefault style="color: red">Ошибка сервера. Напиши админам в дискорде.</p>
</div>
<button mat-button (click)="registerCurrentDiscordUser()">Привязать</button>
</div>
<div *ngIf="currentDiscordData != null && currentDiscordId!='not_exists'">
<p>Сначала нужно удалить текущию связку на предыдущем шаге</p>
</div>
</ng-template>
</mat-step>
</mat-stepper>
</div>
</mat-dialog-content>
<mat-dialog-actions>
</mat-dialog-actions>
`
})
export class DiscordConnectDialog implements AfterViewInit {
currentDiscordId: string|''|'not_exists' = '';
removeDiscordId: number|null = null; //1 удален 0 неудален -1 ошибка нулл не проверяли
stage: 'init' = 'init';
@Input('stepper')
stepper!: MatStepper;
currentDiscordData!: DiscordAccount|null;
currentDiscordDataStatus!: number|null;
//200/201 - успешно
//413 - найден иной не отвязанный стим с тем который хотят привязать
//409 - найден иной не отвязанный дискорд с тем который хотят привязать
registerDiscordStatus!: number|null;
constructor(public authService: AuthService, public actionService: ActionService) {}
ngAfterViewInit(): void {
this.fillCurrentDiscordId();
this.getCurrentDiscordData();
}
fillCurrentDiscordId() {
this.currentDiscordId = '';
this.authService.getCurrentUserDiscord().subscribe(
(id) => {this.currentDiscordId = id;},
(err) => this.currentDiscordId = "not_exists"
)
}
removeCurrentDiscordId() {
this.removeDiscordId = this.removeDiscordId!=-1?null:this.removeDiscordId;
this.authService.removeCurrentUserDiscord().subscribe(
(res) => {
this.removeDiscordId = res?1:0;
this.actionService.showSnack("Аккаунт дискорда был отвязан");
this.fillCurrentDiscordId();
this.stepper.previous();
},
(err) => {
this.removeDiscordId = -1;
this.actionService.showSnack("Произошла ошибка во время удаления аккаунта");
}
)
}
getCurrentDiscordData() {
this.authService.getCurrentUserDiscordData().subscribe(
(res) => {
this.currentDiscordData = res;
this.currentDiscordDataStatus = 200;
console.log(res);
}, (err) => {
this.currentDiscordDataStatus = err.status;
console.log(err);
}
)
}
registerCurrentDiscordUser() {
this.authService.registerCurrentDiscordData().subscribe(
(res) => {
this.registerDiscordStatus = 200;
},
(err) => {
this.registerDiscordStatus = err.status;
}
)
}
}

32
src/app/services/auth.service.ts

@ -5,6 +5,9 @@ import {SteamData} from "../entities/profile/SteamData";
import {SteamIDs} from "../entities/profile/SteamIDs";
import {Permition} from "../entities/profile/Permition";
import {Router} from "@angular/router";
import {map, Observable} from "rxjs";
import {HttpClient} from "@angular/common/http";
import {DiscordAccount} from "../entities/DiscordAccount";
@Injectable({
providedIn: 'root'
@ -15,13 +18,15 @@ export class AuthService {
steamIds: SteamIDs | null = null;
permition: Permition | null = null;
constructor(private playerService: PlayerService, private router: Router) {
constructor(private playerService: PlayerService, private router: Router, private http: HttpClient) {
this.playerService.getProfile(null, [ProfileRequestData.STEAM_DATA, ProfileRequestData.PERMITION])
.subscribe((res) => {
this.steamdata = res.steam_data;
this.steamIds = res.steamids
this.permition = res.permition;
sessionStorage.setItem(AuthService.KEY, JSON.stringify(res.steamids))
}, (err) => {
console.log(err);
})
}
@ -35,6 +40,14 @@ export class AuthService {
window.open("api/auth/logout", "_self")
}
discordLogin() {
window.open("api/auth/discord/login", "_self")
}
discordLogout() {
window.open("api/auth/discord/logout", "_self")
}
isAuth() {
return sessionStorage.getItem(AuthService.KEY) != null;
}
@ -68,4 +81,21 @@ export class AuthService {
(err) => {}
)
}
//discord funcs
getCurrentUserDiscord(): Observable<any> {
return this.http.get(`api/auth/steam/discord`);
}
removeCurrentUserDiscord(): Observable<any> {
return this.http.delete(`api/auth/steam/discord`);
}
getCurrentUserDiscordData(): Observable<any> {
return this.http.get(`api/auth/discord`).pipe(map((res) => DiscordAccount.fromData(res)));
}
registerCurrentDiscordData(): Observable<any> {
return this.http.post(`api/auth/discord`, {});
}
}

Loading…
Cancel
Save