Skip to content

Commit

Permalink
fix(login, inpn): fix login via inpn cas
Browse files Browse the repository at this point in the history
Co-authored-by: jacquesfize <jacques.fize@ecrins-parcnational.fr>
Co-authored-by: Pierre Narcisi <pierre.narcisi@mnhn.fr>
  • Loading branch information
3 people committed Apr 23, 2024
1 parent af7ffbe commit 4af79a4
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 9 deletions.
17 changes: 15 additions & 2 deletions backend/geonature/core/auth/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@
session,
Response,
)
from flask_login import login_user
import sqlalchemy as sa
from sqlalchemy import select
from utils_flask_sqla.response import json_resp

from pypnusershub.db import models
from pypnusershub.db.models import User, Organisme, Application
from pypnusershub.db.tools import encode_token
from pypnusershub.routes import insert_or_update_organism, insert_or_update_role
Expand Down Expand Up @@ -94,7 +97,9 @@ def loginCas():
.id_application
)
token = encode_token(data)
response.set_cookie("token", token, expires=cookie_exp)

token_exp = datetime.datetime.now(datetime.timezone.utc)
token_exp += datetime.timedelta(seconds=current_app.config["COOKIE_EXPIRATION"])

# User cookie
organism_id = info_user["codeOrganisme"]
Expand All @@ -111,7 +116,15 @@ def loginCas():
"id_role": data["id_role"],
"id_organisme": organism_id,
}
response.set_cookie("current_user", str(current_user), expires=cookie_exp)

# Log the user in
user = db.session.execute(
sa.select(models.User)
.where(models.User.identifiant == current_user["user_login"])
.where(models.User.filter_by_app())
).scalar_one()
login_user(user)

return response
else:
log.info("Erreur d'authentification lié au CAS, voir log du CAS")
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export function createTranslateLoader(http: HttpClient) {
import { UserDataService } from './userModule/services/user-data.service';
import { NotificationDataService } from './components/notification/notification-data.service';

import { UserPublicGuard } from '@geonature/modules/login/routes-guard.service';
import { UserCasGuard, UserPublicGuard } from '@geonature/modules/login/routes-guard.service';

export function loadConfig(injector) {
const configService = injector.get(ConfigService);
Expand Down Expand Up @@ -111,6 +111,7 @@ export function initApp(injector) {
],
providers: [
AuthService,
UserCasGuard,
AuthGuard,
ModuleService,
ToastrService,
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/app/components/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export class AuthService {
}

isAuthenticated(): boolean {
return this._cookie.get('token') !== null;
return this._cookie.check('gn_id_token') && this._cookie.get('gn_id_token') !== null;
}

handleLoginError() {
Expand Down
8 changes: 6 additions & 2 deletions frontend/src/app/modules/login/login/login.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { UntypedFormGroup } from '@angular/forms';

import { CommonService } from '@geonature_common/service/common.service';

import { CookieService } from 'ng2-cookies';
import { AuthService } from '../../../components/auth/auth.service';
import { ConfigService } from '@geonature/services/config.service';
import { ModuleService } from '@geonature/services/module.service';
Expand Down Expand Up @@ -34,7 +35,8 @@ export class LoginComponent implements OnInit {
private moduleService: ModuleService,
private router: Router,
private route: ActivatedRoute,
private _routingService: RoutingService
private _routingService: RoutingService,
private _cookie: CookieService
) {
this.enablePublicAccess = this.config.PUBLIC_ACCESS_USERNAME;
this.APP_NAME = this.config.appName;
Expand All @@ -49,7 +51,9 @@ export class LoginComponent implements OnInit {
if (this.config.CAS_PUBLIC.CAS_AUTHENTIFICATION) {
// if token not here here, redirection to CAS login page
const url_redirection_cas = `${this.config.CAS_PUBLIC.CAS_URL_LOGIN}?service=${this.config.API_ENDPOINT}/gn_auth/login_cas`;
document.location.href = url_redirection_cas;
if (!this._authService.isLoggedIn()) {
document.location.href = url_redirection_cas;
}
}
}

Expand Down
46 changes: 45 additions & 1 deletion frontend/src/app/modules/login/routes-guard.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import {
ActivatedRouteSnapshot,
CanActivate,
CanActivateChild,
Router,
RouterStateSnapshot,
UrlTree,
} from '@angular/router';

import { AuthService } from '@geonature/components/auth/auth.service';
import { ConfigService } from '@geonature/services/config.service';
import { Observable } from 'rxjs';

@Injectable()
export class SignUpGuard implements CanActivate {
Expand Down Expand Up @@ -62,3 +71,38 @@ export class UserPublicGuard implements CanActivate {
return true;
}
}

@Injectable()
export class UserCasGuard implements CanActivate, CanActivateChild {
/*
A guard used to prevent public user from accessing certain routes :
- Used to prevent public user from accessing the "/user" route in which the user can see and change its own information
*/

constructor(
private _router: Router,
public authService: AuthService,
public _configService: ConfigService,
private _httpclient: HttpClient
) {}
canActivateChild(
childRoute: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
return this.canActivate();
}

async canActivate(): Promise<boolean> {
let res: boolean = false;
if (this._configService.CAS_PUBLIC.CAS_AUTHENTIFICATION) {
let data = await this._httpclient
.get(`${this._configService.API_ENDPOINT}/auth/get_current_user`)
.toPromise();
data = { ...data };
this.authService.manageUser(data);
res = this.authService.isLoggedIn();
return res;
}
return true;
}
}
7 changes: 6 additions & 1 deletion frontend/src/app/routing/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { HomeContentComponent } from '../components/home-content/home-content.co
import { PageNotFoundComponent } from '../components/page-not-found/page-not-found.component';
import { AuthGuard } from '@geonature/routing/auth-guard.service';
import { ModuleGuardService } from '@geonature/routing/module-guard.service';
import { SignUpGuard, UserPublicGuard } from '@geonature/modules/login/routes-guard.service';
import {
SignUpGuard,
UserCasGuard,
UserPublicGuard,
} from '@geonature/modules/login/routes-guard.service';
import { SignUpComponent } from '../modules/login/sign-up/sign-up.component';

import { UserManagementGuard } from '@geonature/modules/login/routes-guard.service';
Expand Down Expand Up @@ -36,6 +40,7 @@ const defaultRoutes: Routes = [
{
path: '',
component: NavHomeComponent,
canActivate: [UserCasGuard],
canActivateChild: [AuthGuard],
children: [
{
Expand Down

0 comments on commit 4af79a4

Please sign in to comment.