Skip to content

Commit

Permalink
Merge pull request #24 from sentemon/refactoring-the-way-to-set-cookies
Browse files Browse the repository at this point in the history
Refactoring the way to set cookies
  • Loading branch information
sentemon authored Jan 7, 2025
2 parents 0939a8b + 906bff8 commit 6caf14e
Show file tree
Hide file tree
Showing 8 changed files with 88 additions and 80 deletions.
18 changes: 18 additions & 0 deletions backend/src/AuthService/AuthService.Api/GraphQL/Mutation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ public async Task<KeycloakTokenResponse> Register(RegisterDto input, [Service] R
{
throw new GraphQLException(new Error(result.Error.Message));
}

_httpContextAccessor.HttpContext?.Response.Cookies.Append("token", result.Response.AccessToken, new CookieOptions
{
Path = "/",
HttpOnly = false,
Secure = false,
SameSite = SameSiteMode.Strict,
});

return result.Response;
}
Expand All @@ -43,6 +51,14 @@ public async Task<KeycloakTokenResponse> Login(LoginDto input, [Service] LoginCo
throw new GraphQLException(new Error(result.Error.Message));
}

_httpContextAccessor.HttpContext?.Response.Cookies.Append("token", result.Response.AccessToken, new CookieOptions
{
Path = "/",
HttpOnly = false,
Secure = false,
SameSite = SameSiteMode.Strict
});

return result.Response;
}

Expand All @@ -55,6 +71,8 @@ public async Task<string> Logout(string refreshToken, [Service] LogoutCommandHan
{
throw new GraphQLException(new Error(result.Error.Message));
}

_httpContextAccessor.HttpContext?.Response.Cookies.Delete("token");

return result.Response;
}
Expand Down
14 changes: 0 additions & 14 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
"@apollo/client": "^3.11.10",
"apollo-angular": "^8.0.0",
"graphql": "^16.9.0",
"ngx-cookie-service": "^18.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.10"
Expand Down
30 changes: 30 additions & 0 deletions frontend/src/app/apollo.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ApolloClientOptions, InMemoryCache, ApolloLink, HttpLink } from '@apollo/client/core';
import { setContext } from '@apollo/client/link/context';
import { environment } from '../environments/environment';
import {inject} from "@angular/core";
import {CookieService} from "./core/services/cookie.service";

export function createApolloClientOptions(): ApolloClientOptions<any> {
const cookieService = inject(CookieService);

const httpLink = new HttpLink({
uri: environment.auth_service,
credentials: 'include',
});

const authLink = setContext(() => {
const token = cookieService.get("token");
return {
headers: {
Authorization: token ? `Bearer ${token}` : '',
}
};
});

const link = ApolloLink.from([authLink, httpLink]);

return {
link: link,
cache: new InMemoryCache()
};
}
28 changes: 2 additions & 26 deletions frontend/src/app/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@ import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import {provideHttpClient, withFetch} from '@angular/common/http';
import { provideApollo } from 'apollo-angular';
import { ApolloLink, InMemoryCache} from '@apollo/client/core';
import {setContext} from "@apollo/client/link/context";
import {environment} from "../environments/environment";
import {HttpLink} from "apollo-angular/http";
import {loadDevMessages, loadErrorMessages} from "@apollo/client/dev";
import { createApolloClientOptions } from "./apollo.config";

export const appConfig: ApplicationConfig = {
providers: [
Expand All @@ -20,30 +18,8 @@ export const appConfig: ApplicationConfig = {
loadDevMessages();
loadErrorMessages();
}
const httpLink = inject(HttpLink);

const authLink = setContext(() => {
const token = document.cookie
.split('; ')
.find(row => row.startsWith('token='))
?.split('=')[1];
return {

headers: {
Authorization: token ? `Bearer ${token}` : '',
}
};
});

const link = ApolloLink.from([
authLink,
httpLink.create({ uri: environment.auth_service }),
]);

return {
link: link,
cache: new InMemoryCache(),
};
return createApolloClientOptions();
})
]
};
18 changes: 18 additions & 0 deletions frontend/src/app/core/services/cookie.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})
export class CookieService {

constructor() { }

get(key: string): string {
let value = document.cookie
.split('; ')
.find(row => row.startsWith(`${key}=`))
?.split('=')[1];

return value ?? `There is no cookie with key ${key}.`;
}
}
23 changes: 0 additions & 23 deletions frontend/src/app/core/services/token.service.ts

This file was deleted.

36 changes: 20 additions & 16 deletions frontend/src/app/features/auth/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
import {Injectable} from '@angular/core';
import {inject, Injectable} from '@angular/core';
import {Apollo} from "apollo-angular";
import {map, Observable} from "rxjs";
import {BehaviorSubject, map, Observable} from "rxjs";
import {LOGIN, REGISTER} from "../requests/mutations";
import {TokenService} from "../../../core/services/token.service";
import {MutationResponse} from "../responses/mutation.response";
import {QueryResponses} from "../responses/query.responses";
import {IS_AUTHENTICATED} from "../requests/queries";
import {environment} from "../../../../environments/environment";
import {InMemoryCache} from "@apollo/client/core";
import {CookieService} from "../../../core/services/cookie.service";

@Injectable({
providedIn: 'root'
})
export class AuthService {
private isAuthenticatedSubject = new BehaviorSubject<boolean>(this.checkAuth());
public isAuthenticated$ = this.isAuthenticatedSubject.asObservable();

constructor(private apollo: Apollo, private tokenService: TokenService) {
// apollo.create({
// uri: environment.auth_service,
// cache: new InMemoryCache()
// });
constructor(private apollo: Apollo) { }

private checkAuth(): boolean {
let cookieService = inject(CookieService);

const token = cookieService.get("token");

return token != "There is no cookie with key token.";
}

public login(username: string, password: string): Observable<boolean> {
Expand All @@ -30,9 +33,10 @@ export class AuthService {
const token = response.data?.login;

if (token) {
this.tokenService.set(token);
this.isAuthenticatedSubject.next(true);
return true;
} else {
this.isAuthenticatedSubject.next(false);
console.error("Login failed: no token received.");
return false;
}
Expand All @@ -55,7 +59,6 @@ export class AuthService {
const token = response.data?.register;

if (token) {
this.tokenService.set(token);
return true;
} else {
console.error("Registration failed: no token received.");
Expand All @@ -67,9 +70,10 @@ export class AuthService {


public isAuthenticated(): Observable<boolean> {
return this.apollo.query<QueryResponses>({
query: IS_AUTHENTICATED
}).pipe(
map(response => response.data.isAuthenticated));
// return this.apollo.query<QueryResponses>({
// query: IS_AUTHENTICATED
// }).pipe(
// map(response => response.data.isAuthenticated));
return this.isAuthenticated$;
}
}

0 comments on commit 6caf14e

Please sign in to comment.