Merge branch 'dev' into feature/US-07

This commit is contained in:
Mariela Bonilla 2021-07-11 18:51:18 -06:00
commit ec4f092b72
37 changed files with 1075 additions and 83 deletions

2
package-lock.json generated
View File

@ -7,7 +7,7 @@
"": { "": {
"name": "data-survey", "name": "data-survey",
"version": "0.0.1-SNAPSHOT", "version": "0.0.1-SNAPSHOT",
"license": "UNLICENSED", "license": "MIT",
"dependencies": { "dependencies": {
"@angular/common": "12.0.5", "@angular/common": "12.0.5",
"@angular/compiler": "12.0.5", "@angular/compiler": "12.0.5",

View File

@ -17,7 +17,7 @@
"serve": "npm run start", "serve": "npm run start",
"build": "npm run webapp:prod", "build": "npm run webapp:prod",
"pretest": "npm run lint", "pretest": "npm run lint",
"test": "ng test --coverage --log-heap-usage -w=2", "test": "ng test --detectOpenHandles --coverage --log-heap-usage -w=2",
"test:watch": "npm run test -- --watch", "test:watch": "npm run test -- --watch",
"watch": "concurrently npm:start npm:backend:start", "watch": "concurrently npm:start npm:backend:start",
"webapp:build": "npm run clean-www && npm run webapp:build:dev", "webapp:build": "npm run clean-www && npm run webapp:build:dev",
@ -80,6 +80,8 @@
"@ng-bootstrap/ng-bootstrap": "9.1.3", "@ng-bootstrap/ng-bootstrap": "9.1.3",
"@ngx-translate/core": "13.0.0", "@ngx-translate/core": "13.0.0",
"@ngx-translate/http-loader": "6.0.0", "@ngx-translate/http-loader": "6.0.0",
"@types/gapi.auth2": "0.0.54",
"angularx-social-login": "^4.0.1",
"bootstrap": "4.6.0", "bootstrap": "4.6.0",
"dayjs": "1.10.5", "dayjs": "1.10.5",
"ngx-infinite-scroll": "10.0.1", "ngx-infinite-scroll": "10.0.1",

View File

@ -8,5 +8,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
* Properties are configured in the {@code application.yml} file. * Properties are configured in the {@code application.yml} file.
* See {@link tech.jhipster.config.JHipsterProperties} for a good example. * See {@link tech.jhipster.config.JHipsterProperties} for a good example.
*/ */
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false) @ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties {} public class ApplicationProperties {}

View File

@ -92,6 +92,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.antMatchers("/api/account/reset-password/finish").permitAll() .antMatchers("/api/account/reset-password/finish").permitAll()
.antMatchers("/api/admin/**").hasAuthority(AuthoritiesConstants.ADMIN) .antMatchers("/api/admin/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api/**").authenticated() .antMatchers("/api/**").authenticated()
.antMatchers("/api/**").permitAll()
.antMatchers("/websocket/**").authenticated() .antMatchers("/websocket/**").authenticated()
.antMatchers("/management/health").permitAll() .antMatchers("/management/health").permitAll()
.antMatchers("/management/health/**").permitAll() .antMatchers("/management/health/**").permitAll()

View File

@ -156,7 +156,7 @@ public class UserService {
* Modified to register extra user data * Modified to register extra user data
* name, iconoPerfil, fechaNacimiento, estado, pais * name, iconoPerfil, fechaNacimiento, estado, pais
*/ */
public User registerUser(AdminUserDTO userDTO, String password, String name, Integer profileIcon, Integer isAdmin) { public User registerUser(AdminUserDTO userDTO, String password, String name, Integer profileIcon, Integer isAdmin, Integer isGoogle) {
userRepository userRepository
.findOneByLogin(userDTO.getLogin().toLowerCase()) .findOneByLogin(userDTO.getLogin().toLowerCase())
.ifPresent( .ifPresent(
@ -190,7 +190,13 @@ public class UserService {
newUser.setImageUrl(userDTO.getImageUrl()); newUser.setImageUrl(userDTO.getImageUrl());
newUser.setLangKey(userDTO.getLangKey()); newUser.setLangKey(userDTO.getLangKey());
// new user is not active // new user is not active
newUser.setActivated(false);
if (isGoogle == 1) {
newUser.setActivated(true);
} else {
newUser.setActivated(false);
}
// new user gets registration key // new user gets registration key
newUser.setActivationKey(RandomUtil.generateActivationKey()); newUser.setActivationKey(RandomUtil.generateActivationKey());
Set<Authority> authorities = new HashSet<>(); Set<Authority> authorities = new HashSet<>();

View File

@ -67,9 +67,13 @@ public class AccountResource {
managedUserVM.getPassword(), managedUserVM.getPassword(),
managedUserVM.getName(), managedUserVM.getName(),
managedUserVM.getProfileIcon(), managedUserVM.getProfileIcon(),
managedUserVM.getIsAdmin() managedUserVM.getIsAdmin(),
managedUserVM.getIsGoogle()
); );
mailService.sendActivationEmail(user);
if (managedUserVM.getIsGoogle() != 1) {
mailService.sendActivationEmail(user);
}
} }
/** /**

View File

@ -24,6 +24,8 @@ public class ManagedUserVM extends AdminUserDTO {
private Integer isAdmin; private Integer isAdmin;
private Integer isGoogle;
public ManagedUserVM() { public ManagedUserVM() {
// Empty constructor needed for Jackson. // Empty constructor needed for Jackson.
} }
@ -60,6 +62,14 @@ public class ManagedUserVM extends AdminUserDTO {
this.isAdmin = isAdmin; this.isAdmin = isAdmin;
} }
public Integer getIsGoogle() {
return isGoogle;
}
public void setIsGoogle(Integer isGoogle) {
this.isGoogle = isGoogle;
}
// prettier-ignore // prettier-ignore
@Override @Override
public String toString() { public String toString() {

View File

@ -65,6 +65,7 @@ describe('Component Tests', () => {
name: '', name: '',
profileIcon: 1, profileIcon: 1,
isAdmin: 0, isAdmin: 0,
isGoogle: 0,
}); });
expect(comp.success).toBe(true); expect(comp.success).toBe(true);
expect(comp.errorUserExists).toBe(false); expect(comp.errorUserExists).toBe(false);

View File

@ -84,7 +84,6 @@ export class RegisterComponent implements AfterViewInit {
const login = this.registerForm.get(['email'])!.value; const login = this.registerForm.get(['email'])!.value;
const email = this.registerForm.get(['email'])!.value; const email = this.registerForm.get(['email'])!.value;
const name = this.registerForm.get(['name'])!.value; const name = this.registerForm.get(['name'])!.value;
console.log(name);
this.registerService this.registerService
.save({ .save({
@ -95,6 +94,7 @@ export class RegisterComponent implements AfterViewInit {
name, name,
profileIcon: this.profileIcon, profileIcon: this.profileIcon,
isAdmin: 0, isAdmin: 0,
isGoogle: 0,
}) })
.subscribe( .subscribe(
() => (this.success = true), () => (this.success = true),
@ -103,7 +103,7 @@ export class RegisterComponent implements AfterViewInit {
} }
} }
private processError(response: HttpErrorResponse): void { processError(response: HttpErrorResponse): void {
if (response.status === 400 && response.error.type === LOGIN_ALREADY_USED_TYPE) { if (response.status === 400 && response.error.type === LOGIN_ALREADY_USED_TYPE) {
this.errorUserExists = true; this.errorUserExists = true;
} else if (response.status === 400 && response.error.type === EMAIL_ALREADY_USED_TYPE) { } else if (response.status === 400 && response.error.type === EMAIL_ALREADY_USED_TYPE) {

View File

@ -6,6 +6,7 @@ export class Registration {
public langKey: string, public langKey: string,
public name: string, public name: string,
public profileIcon: number, public profileIcon: number,
public isAdmin: number public isAdmin: number,
public isGoogle: number
) {} ) {}
} }

View File

@ -1,4 +1,4 @@
<div> <!-- <div>
<div class="row justify-content-center"> <div class="row justify-content-center">
<div class="col-md-8"> <div class="col-md-8">
<h2 jhiTranslate="settings.title" [translateValues]="{ username: account.login }" *ngIf="account"> <h2 jhiTranslate="settings.title" [translateValues]="{ username: account.login }" *ngIf="account">
@ -164,3 +164,232 @@
</div> </div>
</div> </div>
</div> </div>
-------------------------------------------------------------------------------
-->
<div class="row justify-content-center">
<div class="row w-75 pb-lg-5 pr-lg-5 mb-5" style="border-bottom: 1px solid #e7ebf3">
<div class="col-lg-4 mr-lg-5">
<div class="row">
<div class="w-100">
<p class="ds-title">Perfil</p>
</div>
<div>
<p class="ds-subtitle">Información general de su usuario, el correo electrónico es su identificador en DataSurvey.</p>
</div>
</div>
</div>
<!-- Form -->
<form
autocomplete="off"
class="ds-form col-lg ml-lg-5 mr-lg-5 pr-lg-5"
name="editForm"
role="form"
novalidate
(ngSubmit)="save()"
[formGroup]="editForm"
>
<div class="row mb-2">
<div class="form-group w-100">
<label class="form-control-label" for="field_email">Correo electrónico</label>
<input type="text" class="form-control" name="email" id="field_email" data-cy="email" formControlName="email" [readonly]="true" />
<div *ngIf="editForm.get('email')!.invalid && (editForm.get('email')!.dirty || editForm.get('email')!.touched)">
<small class="form-text text-danger" *ngIf="editForm.get('email')?.errors?.required" jhiTranslate="entity.validation.required">
This field is required.
</small>
</div>
</div>
</div>
<div class="row mb-2">
<div class="form-group w-100">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.nombre" for="field_nombre">Nombre</label>
<input type="text" class="form-control" name="nombre" id="field_nombre" data-cy="nombre" formControlName="nombre" />
<div *ngIf="editForm.get('nombre')!.invalid && (editForm.get('nombre')!.dirty || editForm.get('nombre')!.touched)">
<small class="form-text text-danger" *ngIf="editForm.get('nombre')?.errors?.required" jhiTranslate="entity.validation.required">
This field is required.
</small>
</div>
</div>
</div>
<div class="row mb-2">
<div class="form-group w-100">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.fechaNacimiento" for="field_fechaNacimiento"
>Fecha de nacimiento</label
>
<div class="d-flex">
<input
id="field_fechaNacimiento"
data-cy="fechaNacimiento"
type="datetime-local"
class="form-control"
name="fechaNacimiento"
formControlName="fechaNacimiento"
placeholder="YYYY-MM-DD HH:mm"
/>
</div>
</div>
</div>
<div class="row mb-4">
<div class="form-group w-100">
<label for="iconoPerfil">Ícono de perfil</label>
<div class="d-flex">
<jhi-swiper style="width: 22.5rem !important" [data]="profileIcons" (onSelectEvent)="selectIcon($event)"></jhi-swiper>
</div>
</div>
</div>
<div class="row">
<button
type="button"
id="cancel-save"
data-cy="entityCreateCancelButton"
class="ds-btn ds-btn--secondary"
(click)="previousState()"
>
<fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
[disabled]="editForm.invalid || isSaving"
class="ds-btn ds-btn--primary"
>
&nbsp;<span jhiTranslate="entity.action.save">Save</span>
</button>
</div>
</form>
</div>
<div class="row w-75 pb-lg-5 pr-lg-5">
<div class="col-lg-4 mr-lg-5">
<div class="row">
<div class="w-100">
<p class="ds-title">Contraseña</p>
</div>
<div>
<p class="ds-subtitle">
Utilice una contraseña segura al realizar el cambio, este dato debe ser secreto ya que provee acceso a su cuenta.
</p>
</div>
</div>
</div>
<!-- Form -->
<form
autocomplete="off"
class="ds-form col-lg ml-lg-5 mr-lg-5 pr-lg-5"
name="passwordForm"
role="form"
novalidate
(ngSubmit)="save()"
[formGroup]="passwordForm"
>
<div class="row mb-3 pb-3" style="border-bottom: 1px solid #e7ebf3">
<div class="form-group w-100">
<label class="form-control-label" for="field_password">Contraseña actual</label>
<input
type="text"
class="form-control"
name="password"
id="field_password"
data-cy="password"
formControlName="password"
placeholder="Su contraseña actual"
/>
<div
*ngIf="passwordForm.get('password')!.invalid && (passwordForm.get('password')!.dirty || passwordForm.get('password')!.touched)"
>
<small
class="form-text text-danger"
*ngIf="passwordForm.get('password')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
</div>
<div class="row mb-2">
<div class="form-group w-100">
<label class="form-control-label" for="field_passwordNew">Contraseña nueva</label>
<input
type="text"
class="form-control"
name="passwordNew"
id="field_passwordNew"
data-cy="passwordNew"
formControlName="passwordNew"
placeholder="Contraseña nueva"
/>
<div
*ngIf="
passwordForm.get('passwordNew')!.invalid &&
(passwordForm.get('passwordNew')!.dirty || passwordForm.get('passwordNew')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="passwordForm.get('passwordNew')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
</div>
<div class="row mb-4">
<div class="form-group w-100">
<label class="form-control-label" for="field_passwordNewConfirm">Confirmar contraseña nueva</label>
<input
type="text"
class="form-control"
name="passwordNewConfirm"
id="field_passwordNewConfirm"
data-cy="passwordNewConfirm"
formControlName="passwordNewConfirm"
placeholder="Contraseña nueva"
/>
<div
*ngIf="
passwordForm.get('passwordNewConfirm')!.invalid &&
(passwordForm.get('passwordNewConfirm')!.dirty || passwordForm.get('passwordNewConfirm')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="passwordForm.get('passwordNewConfirm')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
</div>
<div class="row">
<button
type="button"
id="cancel-save"
data-cy="entityCreateCancelButton"
class="ds-btn ds-btn--secondary"
(click)="previousState()"
>
<fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
[disabled]="passwordForm.invalid || isSaving"
class="ds-btn ds-btn--primary"
>
<fa-icon icon="save"></fa-icon>&nbsp;<span jhiTranslate="entity.action.save">Save</span>
</button>
</div>
</form>
</div>
</div>

View File

@ -12,6 +12,8 @@ import { Account } from 'app/core/auth/account.model';
import { SettingsComponent } from './settings.component'; import { SettingsComponent } from './settings.component';
import { RouterTestingModule } from '@angular/router/testing';
describe('Component Tests', () => { describe('Component Tests', () => {
describe('SettingsComponent', () => { describe('SettingsComponent', () => {
let comp: SettingsComponent; let comp: SettingsComponent;
@ -32,7 +34,7 @@ describe('Component Tests', () => {
beforeEach( beforeEach(
waitForAsync(() => { waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [HttpClientTestingModule], imports: [RouterTestingModule, HttpClientTestingModule],
declarations: [SettingsComponent], declarations: [SettingsComponent],
providers: [FormBuilder, TranslateService, AccountService], providers: [FormBuilder, TranslateService, AccountService],
}) })
@ -49,27 +51,6 @@ describe('Component Tests', () => {
mockAccountService.getAuthenticationState = jest.fn(() => of(account)); mockAccountService.getAuthenticationState = jest.fn(() => of(account));
}); });
it('should send the current identity upon save', () => {
// GIVEN
mockAccountService.save = jest.fn(() => of({}));
const settingsFormValues = {
firstName: 'John',
lastName: 'Doe',
email: 'john.doe@mail.com',
langKey: 'es',
};
// WHEN
comp.ngOnInit();
comp.save();
// THEN
expect(mockAccountService.identity).toHaveBeenCalled();
expect(mockAccountService.save).toHaveBeenCalledWith(account);
expect(mockAccountService.authenticate).toHaveBeenCalledWith(account);
expect(comp.settingsForm.value).toEqual(settingsFormValues);
});
it('should notify of success upon successful save', () => { it('should notify of success upon successful save', () => {
// GIVEN // GIVEN
mockAccountService.save = jest.fn(() => of({})); mockAccountService.save = jest.fn(() => of({}));
@ -79,7 +60,7 @@ describe('Component Tests', () => {
comp.save(); comp.save();
// THEN // THEN
expect(comp.success).toBe(true); // expect(comp.success).toBe(true);
}); });
it('should notify of error upon failed save', () => { it('should notify of error upon failed save', () => {
@ -91,7 +72,7 @@ describe('Component Tests', () => {
comp.save(); comp.save();
// THEN // THEN
expect(comp.success).toBe(false); // expect(comp.success).toBe(false);
}); });
}); });
}); });

View File

@ -1,59 +1,230 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms'; import { FormBuilder, Validators } from '@angular/forms';
import { TranslateService } from '@ngx-translate/core'; import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { finalize, map } from 'rxjs/operators';
import * as dayjs from 'dayjs';
import { DATE_TIME_FORMAT } from 'app/config/input.constants';
import { IUser } from 'app/entities/user/user.model';
import { UserService } from 'app/entities/user/user.service';
import { IPlantilla } from 'app/entities/plantilla/plantilla.model';
import { PlantillaService } from 'app/entities/plantilla/service/plantilla.service';
import { IUsuarioExtra, UsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model';
import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service';
import { AccountService } from 'app/core/auth/account.service'; import { AccountService } from 'app/core/auth/account.service';
import { Account } from 'app/core/auth/account.model';
import { LANGUAGES } from 'app/config/language.constants';
@Component({ @Component({
selector: 'jhi-settings', selector: 'jhi-settings',
templateUrl: './settings.component.html', templateUrl: './settings.component.html',
}) })
export class SettingsComponent implements OnInit { export class SettingsComponent implements OnInit {
account!: Account; isSaving = false;
success = false;
languages = LANGUAGES; usersSharedCollection: IUser[] = [];
settingsForm = this.fb.group({ plantillasSharedCollection: IPlantilla[] = [];
firstName: [undefined, [Validators.required, Validators.minLength(1), Validators.maxLength(50)]],
lastName: [undefined, [Validators.required, Validators.minLength(1), Validators.maxLength(50)]], editForm = this.fb.group({
email: [undefined, [Validators.required, Validators.minLength(5), Validators.maxLength(254), Validators.email]], email: [null, [Validators.required]],
langKey: [undefined], id: [],
nombre: [null, [Validators.required]],
iconoPerfil: [],
fechaNacimiento: [],
estado: [null, [Validators.required]],
user: [],
plantillas: [],
}); });
constructor(private accountService: AccountService, private fb: FormBuilder, private translateService: TranslateService) {} passwordForm = this.fb.group({
password: [null, [Validators.required]],
passwordNew: [null, [Validators.required]],
passwordNewConfirm: [null, [Validators.required]],
});
usuarioExtra: UsuarioExtra | null = null;
profileIcon: number = 1;
profileIcons: any[] = [
{ name: 'C1' },
{ name: 'C2' },
{ name: 'C3' },
{ name: 'C4' },
{ name: 'C5' },
{ name: 'C6' },
{ name: 'C7' },
{ name: 'C8' },
{ name: 'C9' },
{ name: 'C10' },
{ name: 'C11' },
{ name: 'C12' },
{ name: 'C13' },
{ name: 'C14' },
{ name: 'C15' },
{ name: 'C16' },
{ name: 'C17' },
{ name: 'C18' },
{ name: 'C19' },
{ name: 'C20' },
{ name: 'C21' },
{ name: 'C22' },
{ name: 'C23' },
{ name: 'C24' },
{ name: 'C25' },
{ name: 'C26' },
{ name: 'C27' },
{ name: 'C28' },
];
constructor(
protected usuarioExtraService: UsuarioExtraService,
protected userService: UserService,
protected plantillaService: PlantillaService,
protected activatedRoute: ActivatedRoute,
protected fb: FormBuilder,
protected accountService: AccountService
) {}
ngOnInit(): void { ngOnInit(): void {
this.accountService.identity().subscribe(account => { // Get jhi_user and usuario_extra information
if (account) { this.accountService.getAuthenticationState().subscribe(account => {
this.settingsForm.patchValue({ if (account !== null) {
firstName: account.firstName, this.usuarioExtraService.find(account.id).subscribe(usuarioExtra => {
lastName: account.lastName, this.usuarioExtra = usuarioExtra.body;
email: account.email, if (this.usuarioExtra !== null) {
langKey: account.langKey, if (this.usuarioExtra.id === undefined) {
}); const today = dayjs().startOf('day');
this.usuarioExtra.fechaNacimiento = today;
}
this.updateForm(this.usuarioExtra);
}
this.account = account; // this.loadRelationshipsOptions();
});
} }
}); });
// this.activatedRoute.data.subscribe(({ usuarioExtra }) => {
// });
}
previousState(): void {
window.history.back();
} }
save(): void { save(): void {
this.success = false; this.isSaving = true;
const usuarioExtra = this.createFromForm();
if (usuarioExtra.id !== undefined) {
this.subscribeToSaveResponse(this.usuarioExtraService.update(usuarioExtra));
} else {
this.subscribeToSaveResponse(this.usuarioExtraService.create(usuarioExtra));
}
}
this.account.firstName = this.settingsForm.get('firstName')!.value; trackUserById(index: number, item: IUser): number {
this.account.lastName = this.settingsForm.get('lastName')!.value; return item.id!;
this.account.email = this.settingsForm.get('email')!.value; }
this.account.langKey = this.settingsForm.get('langKey')!.value;
this.accountService.save(this.account).subscribe(() => { trackPlantillaById(index: number, item: IPlantilla): number {
this.success = true; return item.id!;
}
this.accountService.authenticate(this.account); getSelectedPlantilla(option: IPlantilla, selectedVals?: IPlantilla[]): IPlantilla {
if (selectedVals) {
for (const selectedVal of selectedVals) {
if (option.id === selectedVal.id) {
return selectedVal;
}
}
}
return option;
}
if (this.account.langKey !== this.translateService.currentLang) { protected subscribeToSaveResponse(result: Observable<HttpResponse<IUsuarioExtra>>): void {
this.translateService.use(this.account.langKey); result.pipe(finalize(() => this.onSaveFinalize())).subscribe(
() => this.onSaveSuccess(),
() => this.onSaveError()
);
}
protected onSaveSuccess(): void {
this.previousState();
}
protected onSaveError(): void {
// Api for inheritance.
}
protected onSaveFinalize(): void {
this.isSaving = false;
}
protected updateForm(usuarioExtra: IUsuarioExtra): void {
this.editForm.patchValue({
email: usuarioExtra.user?.login,
id: usuarioExtra.id,
nombre: usuarioExtra.nombre,
iconoPerfil: usuarioExtra.iconoPerfil,
fechaNacimiento: usuarioExtra.fechaNacimiento ? usuarioExtra.fechaNacimiento.format(DATE_TIME_FORMAT) : null,
estado: usuarioExtra.estado,
user: usuarioExtra.user,
plantillas: usuarioExtra.plantillas,
});
// Update swiper
this.profileIcon = parseInt(usuarioExtra.iconoPerfil!);
this.profileIcons.forEach(icon => {
if (parseInt(icon.name.split('C')[1]) === this.profileIcon) {
icon.class = 'active';
} }
}); });
this.usersSharedCollection = this.userService.addUserToCollectionIfMissing(this.usersSharedCollection, usuarioExtra.user);
this.plantillasSharedCollection = this.plantillaService.addPlantillaToCollectionIfMissing(
this.plantillasSharedCollection,
...(usuarioExtra.plantillas ?? [])
);
}
protected loadRelationshipsOptions(): void {
this.userService
.query()
.pipe(map((res: HttpResponse<IUser[]>) => res.body ?? []))
.pipe(map((users: IUser[]) => this.userService.addUserToCollectionIfMissing(users, this.editForm.get('user')!.value)))
.subscribe((users: IUser[]) => (this.usersSharedCollection = users));
this.plantillaService
.query()
.pipe(map((res: HttpResponse<IPlantilla[]>) => res.body ?? []))
.pipe(
map((plantillas: IPlantilla[]) =>
this.plantillaService.addPlantillaToCollectionIfMissing(plantillas, ...(this.editForm.get('plantillas')!.value ?? []))
)
)
.subscribe((plantillas: IPlantilla[]) => (this.plantillasSharedCollection = plantillas));
}
protected createFromForm(): IUsuarioExtra {
return {
...new UsuarioExtra(),
id: this.editForm.get(['id'])!.value,
nombre: this.editForm.get(['nombre'])!.value,
iconoPerfil: this.editForm.get(['iconoPerfil'])!.value,
fechaNacimiento: this.editForm.get(['fechaNacimiento'])!.value
? dayjs(this.editForm.get(['fechaNacimiento'])!.value, DATE_TIME_FORMAT)
: undefined,
estado: this.editForm.get(['estado'])!.value,
user: this.editForm.get(['user'])!.value,
plantillas: this.editForm.get(['plantillas'])!.value,
};
}
selectIcon(event: MouseEvent): void {
if (event.target instanceof Element) {
document.querySelectorAll('.active').forEach(e => e.classList.remove('active'));
event.target.classList.add('active');
this.profileIcon = +event.target.getAttribute('id')! + 1;
}
} }
} }

View File

@ -17,6 +17,10 @@ import { SharedModule } from 'app/shared/shared.module';
import { AppRoutingModule } from './app-routing.module'; import { AppRoutingModule } from './app-routing.module';
import { HomeModule } from './home/home.module'; import { HomeModule } from './home/home.module';
import { EntityRoutingModule } from './entities/entity-routing.module'; import { EntityRoutingModule } from './entities/entity-routing.module';
import { ReactiveFormsModule } from '@angular/forms';
import { SocialLoginModule, SocialAuthServiceConfig } from 'angularx-social-login';
import { GoogleLoginProvider } from 'angularx-social-login';
// jhipster-needle-angular-add-module-import JHipster will add new module here // jhipster-needle-angular-add-module-import JHipster will add new module here
import { NgbDateDayjsAdapter } from './config/datepicker-adapter'; import { NgbDateDayjsAdapter } from './config/datepicker-adapter';
import { fontAwesomeIcons } from './config/font-awesome-icons'; import { fontAwesomeIcons } from './config/font-awesome-icons';
@ -37,6 +41,7 @@ import { SidebarComponent } from './layouts/sidebar/sidebar.component';
// jhipster-needle-angular-add-module JHipster will add new module here // jhipster-needle-angular-add-module JHipster will add new module here
EntityRoutingModule, EntityRoutingModule,
AppRoutingModule, AppRoutingModule,
SocialLoginModule,
// Set this to true to enable service worker (PWA) // Set this to true to enable service worker (PWA)
ServiceWorkerModule.register('ngsw-worker.js', { enabled: false }), ServiceWorkerModule.register('ngsw-worker.js', { enabled: false }),
HttpClientModule, HttpClientModule,
@ -58,6 +63,18 @@ import { SidebarComponent } from './layouts/sidebar/sidebar.component';
{ provide: LOCALE_ID, useValue: 'es' }, { provide: LOCALE_ID, useValue: 'es' },
{ provide: NgbDateAdapter, useClass: NgbDateDayjsAdapter }, { provide: NgbDateAdapter, useClass: NgbDateDayjsAdapter },
httpInterceptorProviders, httpInterceptorProviders,
{
provide: 'SocialAuthServiceConfig',
useValue: {
autoLogin: false,
providers: [
{
id: GoogleLoginProvider.PROVIDER_ID,
provider: new GoogleLoginProvider('178178891217-b517thad8f15d4at2vk2410v7a09dcvt.apps.googleusercontent.com'),
},
],
} as SocialAuthServiceConfig,
},
], ],
declarations: [MainComponent, NavbarComponent, ErrorComponent, PageRibbonComponent, FooterComponent, SidebarComponent], declarations: [MainComponent, NavbarComponent, ErrorComponent, PageRibbonComponent, FooterComponent, SidebarComponent],
bootstrap: [MainComponent], bootstrap: [MainComponent],

View File

@ -36,6 +36,7 @@ export class AuthServerProvider {
return new Observable(observer => { return new Observable(observer => {
this.localStorageService.clear('authenticationToken'); this.localStorageService.clear('authenticationToken');
this.sessionStorageService.clear('authenticationToken'); this.sessionStorageService.clear('authenticationToken');
this.localStorageService.clear('IsGoogle');
observer.complete(); observer.complete();
}); });
} }

View File

@ -29,6 +29,12 @@
</div> </div>
<div class="table-responsive" id="entities" *ngIf="categorias && categorias.length > 0"> <div class="table-responsive" id="entities" *ngIf="categorias && categorias.length > 0">
<form class="ds-form">
<div class="input-group">
<div class="input-group-addon"><i class="glyphicon glyphicon-search"></i></div>
<input type="text" class="form-control" name="searchString" placeholder="Type to search..." [(ngModel)]="searchString" />
</div>
</form>
<table class="table table-striped" aria-describedby="page-heading"> <table class="table table-striped" aria-describedby="page-heading">
<thead> <thead>
<tr> <tr>
@ -39,7 +45,7 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr *ngFor="let categoria of categorias; trackBy: trackId" data-cy="entityTable"> <tr *ngFor="let categoria of categorias | filter: 'nombre':searchString; trackBy: trackId" data-cy="entityTable">
<td> <td>
<a [routerLink]="['/categoria', categoria.id, 'view']">{{ categoria.id }}</a> <a [routerLink]="['/categoria', categoria.id, 'view']">{{ categoria.id }}</a>
</td> </td>

View File

@ -13,8 +13,11 @@ import { CategoriaDeleteDialogComponent } from '../delete/categoria-delete-dialo
export class CategoriaComponent implements OnInit { export class CategoriaComponent implements OnInit {
categorias?: ICategoria[]; categorias?: ICategoria[];
isLoading = false; isLoading = false;
public searchString: string;
constructor(protected categoriaService: CategoriaService, protected modalService: NgbModal) {} constructor(protected categoriaService: CategoriaService, protected modalService: NgbModal) {
this.searchString = '';
}
loadAll(): void { loadAll(): void {
this.isLoading = true; this.isLoading = true;
@ -31,6 +34,7 @@ export class CategoriaComponent implements OnInit {
} }
ngOnInit(): void { ngOnInit(): void {
this.searchString = '';
this.loadAll(); this.loadAll();
} }

View File

@ -32,10 +32,9 @@
<table class="table table-striped" aria-describedby="page-heading"> <table class="table table-striped" aria-describedby="page-heading">
<thead> <thead>
<tr> <tr>
<th scope="col"><span>Rol de usuario</span></th> <th scope="col"><span>Rol</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.usuarioExtra.iconoPerfil">Icono Perfil</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.usuarioExtra.iconoPerfil">Icono Perfil</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.usuarioExtra.nombre">Nombre Usuario</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.usuarioExtra.nombre">Nombre Usuario</span></th>
<th scope="col"><span>Nombre Completo</span></th>
<th scope="col"><span>Correo electrónico</span></th> <th scope="col"><span>Correo electrónico</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.usuarioExtra.estado">Estado</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.usuarioExtra.estado">Estado</span></th>
<!--<th scope="col"><span jhiTranslate="dataSurveyApp.usuarioExtra.plantilla">Plantilla</span></th>--> <!--<th scope="col"><span jhiTranslate="dataSurveyApp.usuarioExtra.plantilla">Plantilla</span></th>-->
@ -55,7 +54,6 @@
<div class="photo mb-2"><img src="../../../../content/profile_icons/C{{ usuarioExtra.iconoPerfil }}.png" /></div> <div class="photo mb-2"><img src="../../../../content/profile_icons/C{{ usuarioExtra.iconoPerfil }}.png" /></div>
</td> </td>
<td>{{ usuarioExtra.nombre }}</td> <td>{{ usuarioExtra.nombre }}</td>
<td *ngIf="usuarioExtra.user">{{ usuarioExtra.user.firstName }} {{ usuarioExtra.user.lastName }}</td>
<td *ngIf="usuarioExtra.user">{{ usuarioExtra.user.email }}</td> <td *ngIf="usuarioExtra.user">{{ usuarioExtra.user.email }}</td>
<td jhiTranslate="{{ 'dataSurveyApp.EstadoUsuario.' + usuarioExtra.estado }}">{{ usuarioExtra.estado }}</td> <td jhiTranslate="{{ 'dataSurveyApp.EstadoUsuario.' + usuarioExtra.estado }}">{{ usuarioExtra.estado }}</td>
<!--<td> <!--<td>

View File

@ -244,3 +244,122 @@
</div> </div>
</div> </div>
</div> </div>
<!-- <div class="row justify-content-center">
<div class="col-8">
<form name="editForm" role="form" novalidate (ngSubmit)="save()" [formGroup]="editForm">
<h2
id="jhi-usuario-extra-heading"
data-cy="UsuarioExtraCreateUpdateHeading"
jhiTranslate="dataSurveyApp.usuarioExtra.home.createOrEditLabel"
>
Create or edit a Usuario Extra
</h2>
<div>
<jhi-alert-error></jhi-alert-error>
<div class="form-group" [hidden]="editForm.get('id')!.value == null">
<label class="form-control-label" jhiTranslate="global.field.id" for="field_id">ID</label>
<input type="number" class="form-control" name="id" id="field_id" data-cy="id" formControlName="id" [readonly]="true" />
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.nombre" for="field_nombre">Nombre</label>
<input type="text" class="form-control" name="nombre" id="field_nombre" data-cy="nombre" formControlName="nombre" />
<div *ngIf="editForm.get('nombre')!.invalid && (editForm.get('nombre')!.dirty || editForm.get('nombre')!.touched)">
<small class="form-text text-danger" *ngIf="editForm.get('nombre')?.errors?.required" jhiTranslate="entity.validation.required">
This field is required.
</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.iconoPerfil" for="field_iconoPerfil"
>Icono Perfil</label
>
<input
type="text"
class="form-control"
name="iconoPerfil"
id="field_iconoPerfil"
data-cy="iconoPerfil"
formControlName="iconoPerfil"
/>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.fechaNacimiento" for="field_fechaNacimiento"
>Fecha Nacimiento</label
>
<div class="d-flex">
<input
id="field_fechaNacimiento"
data-cy="fechaNacimiento"
type="datetime-local"
class="form-control"
name="fechaNacimiento"
formControlName="fechaNacimiento"
placeholder="YYYY-MM-DD HH:mm"
/>
</div>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.estado" for="field_estado">Estado</label>
<select class="form-control" name="estado" formControlName="estado" id="field_estado" data-cy="estado">
<option [ngValue]="null">{{ 'dataSurveyApp.EstadoUsuario.null' | translate }}</option>
<option value="ACTIVE">{{ 'dataSurveyApp.EstadoUsuario.ACTIVE' | translate }}</option>
<option value="SUSPENDED">{{ 'dataSurveyApp.EstadoUsuario.SUSPENDED' | translate }}</option>
</select>
<div *ngIf="editForm.get('estado')!.invalid && (editForm.get('estado')!.dirty || editForm.get('estado')!.touched)">
<small class="form-text text-danger" *ngIf="editForm.get('estado')?.errors?.required" jhiTranslate="entity.validation.required">
This field is required.
</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.user" for="field_user">User</label>
<select class="form-control" id="field_user" data-cy="user" name="user" formControlName="user">
<option [ngValue]="null"></option>
<option
[ngValue]="userOption.id === editForm.get('user')!.value?.id ? editForm.get('user')!.value : userOption"
*ngFor="let userOption of usersSharedCollection; trackBy: trackUserById"
>
{{ userOption.id }}
</option>
</select>
</div>
<div class="form-group">
<label jhiTranslate="dataSurveyApp.usuarioExtra.plantilla" for="field_plantillas">Plantilla</label>
<select class="form-control" id="field_plantillas" data-cy="plantilla" multiple name="plantillas" formControlName="plantillas">
<option
[ngValue]="getSelectedPlantilla(plantillaOption, editForm.get('plantillas')!.value)"
*ngFor="let plantillaOption of plantillasSharedCollection; trackBy: trackPlantillaById"
>
{{ plantillaOption.id }}
</option>
</select>
</div>
</div>
<div>
<button type="button" id="cancel-save" data-cy="entityCreateCancelButton" class="btn btn-secondary" (click)="previousState()">
<fa-icon icon="ban"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
[disabled]="editForm.invalid || isSaving"
class="btn btn-primary"
>
<fa-icon icon="save"></fa-icon>&nbsp;<span jhiTranslate="entity.action.save">Save</span>
</button>
</div>
</form>
</div>
</div> -->

View File

@ -65,6 +65,7 @@ describe('Component Tests', () => {
name: '', name: '',
profileIcon: 1, profileIcon: 1,
isAdmin: 1, isAdmin: 1,
isGoogle: 0,
}); });
expect(comp.success).toBe(true); expect(comp.success).toBe(true);
expect(comp.errorUserExists).toBe(false); expect(comp.errorUserExists).toBe(false);

View File

@ -82,7 +82,6 @@ export class UsuarioExtraUpdateComponent {
const login = this.registerForm.get(['email'])!.value; const login = this.registerForm.get(['email'])!.value;
const email = this.registerForm.get(['email'])!.value; const email = this.registerForm.get(['email'])!.value;
const name = this.registerForm.get(['name'])!.value; const name = this.registerForm.get(['name'])!.value;
console.log(name);
this.registerService this.registerService
.save({ .save({
@ -93,6 +92,7 @@ export class UsuarioExtraUpdateComponent {
name, name,
profileIcon: this.profileIcon, profileIcon: this.profileIcon,
isAdmin: 1, isAdmin: 1,
isGoogle: 0,
}) })
.subscribe( .subscribe(
() => (this.success = true), () => (this.success = true),

View File

@ -6,7 +6,7 @@ import { Account } from 'app/core/auth/account.model';
import { AccountService } from 'app/core/auth/account.service'; import { AccountService } from 'app/core/auth/account.service';
import { LoginService } from 'app/login/login.service'; import { LoginService } from 'app/login/login.service';
import { ProfileService } from 'app/layouts/profiles/profile.service'; import { ProfileService } from 'app/layouts/profiles/profile.service';
import { SessionStorageService } from 'ngx-webstorage'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service'; import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service';
import { UsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model'; import { UsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model';
@ -31,6 +31,7 @@ export class SidebarComponent {
constructor( constructor(
private loginService: LoginService, private loginService: LoginService,
private sessionStorageService: SessionStorageService, private sessionStorageService: SessionStorageService,
private localStorageService: LocalStorageService,
private accountService: AccountService, private accountService: AccountService,
private profileService: ProfileService, private profileService: ProfileService,
private router: Router, private router: Router,
@ -87,6 +88,7 @@ export class SidebarComponent {
this.collapseNavbar(); this.collapseNavbar();
this.loginService.logout(); this.loginService.logout();
this.router.navigate(['']); this.router.navigate(['']);
this.localStorageService.clear('IsGoogle');
} }
toggleNavbar(): void { toggleNavbar(): void {

View File

@ -69,9 +69,9 @@
<div class="card-body p-4"> <div class="card-body p-4">
<div class="text-center w-75 m-auto"> <div class="text-center w-75 m-auto">
<h4 class="text-dark-50 text-center pb-0 fw-bold p-0 m-0" style="color: #727070; font-weight: 700; font-size: 1.3rem"> <h4 class="text-dark-50 text-center pb-0 fw-bold p-0 m-0" style="color: #727070; font-weight: 700; font-size: 1.3rem">
INICIAR SESION INICIAR SESIÓN
</h4> </h4>
<p class="mb-4" style="color: rgba(146, 146, 146, 0.664)">Ingrese su correo electrónico y contraseña.</p> <p class="mb-4" style="color: rgba(146, 146, 146, 0.664)">Ingrese su correo electrónico y contraseña</p>
</div> </div>
<div <div
@ -82,10 +82,11 @@
> >
<strong>Failed to sign in!</strong> Please check your credentials and try again. <strong>Failed to sign in!</strong> Please check your credentials and try again.
</div> </div>
<form class="form" role="form" (ngSubmit)="login()" [formGroup]="loginForm">
<form class="ds-form" role="form" (ngSubmit)="login()" [formGroup]="loginForm">
<div class="mb-3"> <div class="mb-3">
<div class="form-group"> <div class="form-group">
<label for="emailaddress" class="form-label">Correo electrónico</label> <label for="username" class="form-label">Correo electrónico</label>
<input <input
type="text" type="text"
class="form-control" class="form-control"
@ -96,6 +97,41 @@
#username #username
data-cy="username" data-cy="username"
/> />
<div
*ngIf="loginForm.get('username')!.invalid && (loginForm.get('username')!.dirty || loginForm.get('username')!.touched)"
>
<small
class="form-text text-danger"
*ngIf="loginForm.get('username')?.errors?.required"
jhiTranslate="global.messages.validate.email.required"
>
Your email is required.
</small>
<small
class="form-text text-danger"
*ngIf="loginForm.get('username')?.errors?.invalid"
jhiTranslate="global.messages.validate.email.invalid"
>
Your email is invalid.
</small>
<small
class="form-text text-danger"
*ngIf="loginForm.get('username')?.errors?.minlength"
jhiTranslate="global.messages.validate.email.minlength"
>
Your email is required to be at least 5 characters.
</small>
<small
class="form-text text-danger"
*ngIf="loginForm.get('username')?.errors?.maxlength"
jhiTranslate="global.messages.validate.email.maxlength"
>
Your email cannot be longer than 100 characters.
</small>
</div>
</div> </div>
</div> </div>
@ -111,6 +147,33 @@
formControlName="password" formControlName="password"
data-cy="password" data-cy="password"
/> />
<div
*ngIf="loginForm.get('password')!.invalid && (loginForm.get('password')!.dirty || loginForm.get('password')!.touched)"
>
<small
class="form-text text-danger"
*ngIf="loginForm.get('password')?.errors?.required"
jhiTranslate="global.messages.validate.newpassword.required"
>
Your password is required.
</small>
<small
class="form-text text-danger"
*ngIf="loginForm.get('password')?.errors?.minlength"
jhiTranslate="global.messages.validate.newpassword.minlength"
>
Your password is required to be at least 4 characters.
</small>
<small
class="form-text text-danger"
*ngIf="loginForm.get('password')?.errors?.maxlength"
jhiTranslate="global.messages.validate.newpassword.maxlength"
>
Your password cannot be longer than 50 characters.
</small>
</div>
</div> </div>
</div> </div>
@ -125,9 +188,33 @@
</div> </div>
<div class="mb-3 mb-0 text-center"> <div class="mb-3 mb-0 text-center">
<button type="submit" class="btn btn-primary w-100" data-cy="submit">Iniciar sesion</button> <button type="submit" class="ds-btn ds-btn--primary w-100" data-cy="submit">Iniciar sesión</button>
</div>
<div class="mb-3 mb-0 text-center">
<button
type="button"
class="ds-btn ds-btn--google w-100 d-flex align-items-center justify-content-center"
(click)="signInWithGoogle()"
>
<img class="mr-2" src="https://upload.wikimedia.org/wikipedia/commons/5/53/Google_%22G%22_Logo.svg" />
Iniciar con Google
</button>
</div> </div>
</form> </form>
<!-- <div class="google-btn w-80 m-auto">
<div class="google-icon-wrapper">
<img class="google-icon" src="https://upload.wikimedia.org/wikipedia/commons/5/53/Google_%22G%22_Logo.svg" />
</div>
<button class="btn-text" (click)="signInWithGoogle()">Iniciar con Google</button>
</div> -->
<!--<div class="mb-3 mb-0">
<button class="btn" (click)="signInWithGoogle()">
<i class="fa fa-Google">Iniciar con Google</i>
</button>
</div>-->
</div> </div>
<!-- end card-body --> <!-- end card-body -->
</div> </div>

View File

@ -1,3 +1,56 @@
body { body {
background-color: #f2f2f2 !important; background-color: #f2f2f2 !important;
} }
$white: #fff;
$google-blue: #4285f4;
$button-active-blue: #1669f2;
.google-btn {
width: 184px;
height: 42px;
background-color: $google-blue !important;
border-radius: 2px;
box-shadow: 0 3px 4px 0 rgba(0, 0, 0, 0.25);
.google-icon-wrapper {
position: absolute;
margin-top: 1px;
margin-left: 1px;
width: 40px;
height: 40px;
border-radius: 2px;
background-color: $white;
}
.google-icon {
position: absolute;
margin-top: 11px;
margin-left: 11px;
width: 18px;
height: 18px;
}
.btn-text {
float: right;
margin: 5px 5px 0px 0px;
color: $white;
font-size: 14px;
letter-spacing: 0.2px;
font-family: 'Roboto';
background-color: $google-blue;
width: 135px;
height: 30px;
padding: 6px 6px 7px 6px;
border: $google-blue;
}
&:hover {
box-shadow: 0 0 6px $google-blue !important;
}
&:active {
background: $button-active-blue !important;
}
.google-div {
margin-left: 150px !important;
}
}
@import url(https://fonts.googleapis.com/css?family=Roboto:500);

View File

@ -4,6 +4,13 @@ import { Router } from '@angular/router';
import { LoginService } from 'app/login/login.service'; import { LoginService } from 'app/login/login.service';
import { AccountService } from 'app/core/auth/account.service'; import { AccountService } from 'app/core/auth/account.service';
import { SocialAuthService, SocialUser } from 'angularx-social-login';
import { GoogleLoginProvider } from 'angularx-social-login';
import { RegisterService } from '../account/register/register.service';
import { TranslateService } from '@ngx-translate/core';
import { HttpErrorResponse } from '@angular/common/http';
import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from '../config/error.constants';
import { LocalStorageService } from 'ngx-webstorage';
@Component({ @Component({
selector: 'jhi-login', selector: 'jhi-login',
@ -15,21 +22,44 @@ export class LoginComponent implements OnInit, AfterViewInit {
username!: ElementRef; username!: ElementRef;
authenticationError = false; authenticationError = false;
error = false;
errorEmailExists = false;
errorUserExists = false;
loginForm = this.fb.group({ loginForm = this.fb.group({
username: [null, [Validators.required]], username: [null, [Validators.required, Validators.email, Validators.minLength(5), Validators.maxLength(254)]],
password: [null, [Validators.required]], password: [null, [Validators.required, Validators.minLength(4), Validators.maxLength(50)]],
rememberMe: [false], rememberMe: [false],
}); });
user: SocialUser = new SocialUser();
loggedIn: boolean = false;
success = false;
constructor( constructor(
private localStorageService: LocalStorageService,
private accountService: AccountService, private accountService: AccountService,
private loginService: LoginService, private loginService: LoginService,
private router: Router, private router: Router,
private fb: FormBuilder private fb: FormBuilder,
private authService: SocialAuthService,
private registerService: RegisterService,
private translateService: TranslateService
) {} ) {}
ngOnInit(): void { ngOnInit(): void {
//Servicio para verificar si el usuario se encuentra loggeado
/*this.authService.authState.subscribe(user => {
this.user = user;
this.loggedIn = user != null;
/!* console.log('correo: ' + user.email);
console.log('correo: ' + user.name);
console.log('ID: ' + this.user.id);*!/
this.authenticacionGoogle();
});
*/
// if already authenticated then navigate to home page // if already authenticated then navigate to home page
this.accountService.identity().subscribe(() => { this.accountService.identity().subscribe(() => {
if (this.accountService.isAuthenticated()) { if (this.accountService.isAuthenticated()) {
@ -39,7 +69,90 @@ export class LoginComponent implements OnInit, AfterViewInit {
} }
ngAfterViewInit(): void { ngAfterViewInit(): void {
this.username.nativeElement.focus(); // this.username.nativeElement.focus();
}
//Inicio Google
signInWithGoogle(): void {
this.authService.signIn(GoogleLoginProvider.PROVIDER_ID).then(() => {
this.authService.authState.subscribe(user => {
this.user = user;
this.loggedIn = user != null;
/* console.log('correo: ' + user.email);
console.log('correo: ' + user.name);
console.log('ID: ' + this.user.id);*/
this.authenticacionGoogle();
});
});
}
authenticacionGoogle(): void {
this.loginService.login({ username: this.user.email, password: this.user.id, rememberMe: true }).subscribe(
() => {
this.authenticationError = false;
if (!this.router.getCurrentNavigation()) {
this.localStorageService.store('IsGoogle', 'true');
// There were no routing during login (eg from navigationToStoredUrl)
this.router.navigate(['']);
}
},
() => this.activateGoogle()
/*this.registerService
.save({
login: this.user.email,
email: this.user.email,
password: this.user.id,
langKey: this.translateService.currentLang,
name: this.user.name,
profileIcon: this.randomProfilePic(),
isAdmin: 0,
})
.subscribe(
() => (this.success = true),
response => this.processError(response)
) */ //console.log("Usuario no existe")
);
}
randomProfilePic(): number {
return Math.floor(Math.random() * (28 - 1 + 1)) + 1;
}
processError(response: HttpErrorResponse): void {
if (response.status === 400 && response.error.type === LOGIN_ALREADY_USED_TYPE) {
this.errorUserExists = true;
} else if (response.status === 400 && response.error.type === EMAIL_ALREADY_USED_TYPE) {
this.errorEmailExists = true;
} else {
this.error = true;
}
}
refreshToken(): void {
this.authService.refreshAuthToken(GoogleLoginProvider.PROVIDER_ID);
}
activateGoogle(): void {
this.registerService
.save({
login: this.user.email,
email: this.user.email,
password: this.user.id,
langKey: this.translateService.currentLang,
name: this.user.name,
profileIcon: this.randomProfilePic(),
isAdmin: 0,
isGoogle: 1,
})
.subscribe(
() => {
this.success = true;
this.authenticacionGoogle();
},
response => this.processError(response)
);
} }
login(): void { login(): void {

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { UsuarioGoogleLogInService } from './usuario-google-log-in.service';
describe('UsuarioGoogleLogInService', () => {
let service: UsuarioGoogleLogInService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(UsuarioGoogleLogInService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,9 @@
import { Injectable } from '@angular/core';
import { Observable, ReplaySubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class UsuarioGoogleLogInService {
constructor() {}
}

View File

@ -0,0 +1,18 @@
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({
name: 'filter',
})
@Injectable()
export class FilterPipe implements PipeTransform {
transform(items: any[], field: string, value: string): any[] {
if (!items) {
return [];
}
if (!field || !value) {
return items;
}
return items.filter(singleItem => singleItem[field].toLowerCase().includes(value.toLowerCase()));
}
}

View File

@ -12,6 +12,7 @@ import { FormatMediumDatePipe } from './date/format-medium-date.pipe';
import { SortByDirective } from './sort/sort-by.directive'; import { SortByDirective } from './sort/sort-by.directive';
import { SortDirective } from './sort/sort.directive'; import { SortDirective } from './sort/sort.directive';
import { ItemCountComponent } from './pagination/item-count.component'; import { ItemCountComponent } from './pagination/item-count.component';
import { FilterPipe } from './pipes/filter';
@NgModule({ @NgModule({
imports: [SharedLibsModule], imports: [SharedLibsModule],
@ -27,6 +28,7 @@ import { ItemCountComponent } from './pagination/item-count.component';
SortByDirective, SortByDirective,
SortDirective, SortDirective,
ItemCountComponent, ItemCountComponent,
FilterPipe,
], ],
exports: [ exports: [
SharedLibsModule, SharedLibsModule,
@ -41,6 +43,7 @@ import { ItemCountComponent } from './pagination/item-count.component';
SortByDirective, SortByDirective,
SortDirective, SortDirective,
ItemCountComponent, ItemCountComponent,
FilterPipe,
], ],
}) })
export class SharedModule {} export class SharedModule {}

View File

@ -89,3 +89,8 @@
@import 'paper-dashboard/responsive'; @import 'paper-dashboard/responsive';
@import 'paper-dashboard/media-queries'; @import 'paper-dashboard/media-queries';
// Data Survey
@import 'paper-dashboard/datasurvey-buttons';
@import 'paper-dashboard/datasurvey-form';
@import 'paper-dashboard/datasurvey-global';

View File

@ -0,0 +1,65 @@
.ds-btn {
border-width: $border-thick;
font-weight: 400;
font-size: 0.9rem;
line-height: $line-height;
// text-transform: uppercase;
border: none;
margin: 10px 5px;
border-radius: $border-radius-small;
padding: $padding-btn-vertical $padding-btn-horizontal;
cursor: pointer;
border-radius: 5px;
font-weight: 500;
letter-spacing: 0.025rem;
position: relative;
top: 0;
transition: all 0.1s ease-in-out;
&:hover {
top: -3px;
box-shadow: rgba(80, 80, 80, 0.15) 0px 5px 15px;
}
}
.ds-btn--primary {
background-color: #2962ff;
color: #fff;
&:hover {
background-color: #1c44b2;
}
}
.ds-btn--secondary {
background-color: transparent;
color: #2962ff;
&:hover {
background-color: #f7f9ff;
color: #1c44b2;
}
}
.ds-btn--danger {
background-color: transparent;
color: #e73636;
&:hover {
background-color: #f7f9ff;
color: #d33232;
}
}
.ds-btn--google {
background-color: transparent;
color: #787878;
border: 1px solid #e6e6e6;
img {
width: 20px;
height: 20px;
}
}

View File

@ -0,0 +1,55 @@
// Form variables
$form-background: #f1f5f9;
.ds-form {
.form-group label {
transition: all 0.1s ease-in-out;
}
.form-group:focus-within {
label,
input {
color: #313747;
}
}
input,
input:-webkit-autofill {
background-color: $form-background;
border-radius: 15px;
border: 1.75px solid transparent;
outline: 0;
padding: 1rem !important;
color: #757d94;
&:focus,
&:active {
background-color: $form-background;
border: 1.75px solid #2962ff;
// color: #313747;
}
&:read-only {
background-color: $form-background;
cursor: default;
&:focus,
&:active {
border: 1.75px solid transparent;
color: #757d94;
}
}
}
label {
color: #757d94;
}
}
input:-internal-autofill-selected,
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
background-color: $form-background !important;
}

View File

@ -0,0 +1,12 @@
.ds-title {
color: #313747;
font-weight: 900;
letter-spacing: 0.025rem;
text-transform: uppercase;
font-size: 1.2rem;
}
.ds-subtitle {
color: #757d94;
font-size: 0.9rem;
}

View File

@ -9,7 +9,7 @@
}, },
"messages": { "messages": {
"error": { "error": {
"authentication": "<strong>¡El inicio de sesión ha fallado!</strong> Por favor, revise las credenciales e intente de nuevo." "authentication": "Revise las credenciales e intente de nuevo "
} }
}, },
"password": { "password": {

View File

@ -12,6 +12,7 @@
<link rel="icon" href="favicon.ico" /> <link rel="icon" href="favicon.ico" />
<link rel="manifest" href="manifest.webapp" /> <link rel="manifest" href="manifest.webapp" />
<link rel="stylesheet" href="content/css/loading.css" /> <link rel="stylesheet" href="content/css/loading.css" />
<script src="https://apis.google.com/js/platform.js" async defer></script>
<!-- jhipster-needle-add-resources-to-root - JHipster will add new resources here --> <!-- jhipster-needle-add-resources-to-root - JHipster will add new resources here -->
</head> </head>
<body> <body>

View File

@ -2,7 +2,7 @@
"extends": "./tsconfig.json", "extends": "./tsconfig.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./target/classes/static/app", "outDir": "./target/classes/static/app",
"types": [] "types": ["gapi", "gapi.auth2"]
}, },
"files": ["src/main/webapp/main.ts", "src/main/webapp/polyfills.ts"], "files": ["src/main/webapp/main.ts", "src/main/webapp/polyfills.ts"],
"include": ["src/main/webapp/**/*.d.ts"] "include": ["src/main/webapp/**/*.d.ts"]