Compare commits

..

5 Commits

Author SHA1 Message Date
kusowl
0427d1c62d feature: user can login to backend 2026-02-23 18:46:23 +05:30
kusowl
aee7e4fd89 navigate user after successful registration.
- data is passed via state
2026-02-23 16:10:59 +05:30
kusowl
4aba99fcb5 chore: format 2026-02-23 15:08:06 +05:30
kusowl
78bf326622 add client side validation errors 2026-02-23 15:07:43 +05:30
kusowl
77532aaac2 Show server side validation errors 2026-02-23 12:17:14 +05:30
20 changed files with 301 additions and 77 deletions

3
.oxfmtrc.json Normal file
View File

@ -0,0 +1,3 @@
{
"ignorePatterns": ["backend/**", "*.min.js"]
}

View File

@ -2,7 +2,13 @@ import { ApplicationConfig, provideBrowserGlobalErrorListeners } from "@angular/
import { provideRouter } from "@angular/router";
import { routes } from "./app.routes";
import { provideHttpClient, withFetch, withInterceptors } from "@angular/common/http";
import { authInterceptor } from "./core/interceptors/auth-interceptor";
export const appConfig: ApplicationConfig = {
providers: [provideBrowserGlobalErrorListeners(), provideRouter(routes)],
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
],
};

View File

@ -0,0 +1,17 @@
import { TestBed } from "@angular/core/testing";
import { HttpInterceptorFn } from "@angular/common/http";
import { authInterceptor } from "./auth-interceptor";
describe("authInterceptor", () => {
const interceptor: HttpInterceptorFn = (req, next) =>
TestBed.runInInjectionContext(() => authInterceptor(req, next));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it("should be created", () => {
expect(interceptor).toBeTruthy();
});
});

View File

@ -0,0 +1,20 @@
import { HttpInterceptorFn } from "@angular/common/http";
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const getCookie = (name: string): string | null => {
const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
return match ? decodeURIComponent(match[3]) : null;
};
let headers = req.headers.set("Accept", "application/json");
const xsrfToken = getCookie("XSRF-TOKEN");
if (xsrfToken) {
headers = headers.set("X-XSRF-TOKEN", xsrfToken);
}
const clonedRequest = req.clone({
withCredentials: true,
headers: headers,
});
return next(clonedRequest);
};

View File

@ -33,7 +33,7 @@
</div>
</nav>
<ul class="dropdown" popover id="popover-1" style="position-anchor: --anchor-1">
<li><a class="block h-full w-full" href="">Login</a></li>
<li><a routerLink="/login" class="block h-full w-full" href="">Login</a></li>
<li><a class="block h-full w-full" href="">My Account</a></li>
<li><a class="block h-full w-full" href="">Orders</a></li>
<li><a class="block h-full w-full" href="">Wishlist</a></li>

View File

@ -1,8 +1,9 @@
import { Component } from "@angular/core";
import { LucideAngularModule, User, ShoppingCart, Search } from "lucide-angular";
import { RouterLink } from "@angular/router";
@Component({
selector: "app-header",
imports: [LucideAngularModule],
imports: [LucideAngularModule, RouterLink],
templateUrl: "./header.html",
styleUrl: "./header.css",
})

View File

@ -1,7 +1,12 @@
import { InjectionToken } from "@angular/core";
import {environment} from '../../../environments/environment';
import { environment } from "../../../environments/environment";
export const API_URL = new InjectionToken<string>('API_URL', {
export const API_URL = new InjectionToken<string>("API_URL", {
providedIn: "root",
factory: () => environment.apiUrl
})
factory: () => environment.apiUrl,
});
export const BACKEND_URL = new InjectionToken<string>("API_URL", {
providedIn: "root",
factory: () => environment.backendUrl,
});

View File

@ -1,4 +1,11 @@
<section class="my-10 sm:my-20 flex justify-center items-center">
@if (successMessage) {
<div
class="px-4 py-3 mb-8 bg-teal-100 rounded-lg text-teal-800 text-sm mt-10 max-w-11/12 sm:max-w-8/12 mx-auto"
>
<p>{{successMessage}}</p>
</div>
}
<section class="my-5 sm:my-10 flex justify-center items-center">
<article class="card max-w-11/12 sm:max-w-8/12 grid md:grid-cols-2 lg:grid-cols-3 gap-4">
<div class="md:col-span-1 lg:col-span-2">
<img
@ -13,21 +20,25 @@
<h2 class="text-xl text-gray-600">Get access to your Orders, Wishlist and Recommendations</h2>
<form class="flex flex-col space-y-5">
<form [formGroup]="loginForm" (ngSubmit)="loginUser()" class="flex flex-col space-y-5">
<fieldset class="fieldset">
<legend class="fieldset-legend">Email</legend>
<input type="text" class="input" placeholder="Enter email here" />
<input formControlName="email" type="text" class="input" placeholder="Enter email here" />
<p class="label">your-email-address@email.com</p>
<app-error fieldName="email" [control]="loginForm.get('email')" />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend">Password</legend>
<input type="password" class="input" placeholder="Type here" />
<input formControlName="password" type="password" class="input" placeholder="Type here" />
<app-error fieldName="password" [control]="loginForm.get('password')" />
</fieldset>
<button type="submit" class="btn btn-black py-2">Login</button>
</form>
<a href="" class="text-xs text-gray-800 text-center w-full block hover:text-teal-600"
<a
routerLink="/register"
class="text-xs text-gray-800 text-center w-full block hover:text-teal-600"
>New User ? Sign Up</a
>
</article>

View File

@ -1,9 +1,38 @@
import { Component } from "@angular/core";
import { Component, inject } from "@angular/core";
import { Router, RouterLink } from "@angular/router";
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms";
import { AuthService } from "../../services/auth-service";
import { Error } from "../../../../shared/components/error/error";
@Component({
selector: "app-login",
imports: [],
imports: [RouterLink, ReactiveFormsModule, Error],
templateUrl: "./login.html",
styleUrl: "./login.css",
})
export class Login {}
export class Login {
successMessage: string | undefined;
authService = inject(AuthService);
loginForm = new FormGroup({
email: new FormControl("", { validators: [Validators.required, Validators.email] }),
password: new FormControl("", { validators: [Validators.required] }),
});
constructor(private router: Router) {
const navigator = this.router.currentNavigation();
const state = navigator?.extras.state as { message?: string };
this.successMessage = state?.message;
}
loginUser() {
if (this.loginForm.invalid) {
this.loginForm.markAllAsTouched();
return;
}
this.authService.login(this.loginForm.value as { email: string; password: string }).subscribe({
next: () => console.log("success"),
});
}
}

View File

@ -1,44 +1,82 @@
<section class="my-10 sm:my-30 flex flex-col sm:flex-row space-x-20 justify-center items-center">
<section
class="my-10 md:my-30 flex flex-col md:flex-row space-x-20 space-y-10 justify-center items-center"
>
<article class="space-y-6">
<h1 class="text-3xl text-gray-800 font-space font-bold">Register</h1>
<h2 class="text-xl text-gray-600">Sign up with your<br />email address to get started</h2>
<div class="text-xs text-red-600 space-y-2">
@for (error of errors(); track error) {
<p>{{ error }}</p>
}
</div>
</article>
<form [formGroup]="registerForm" (ngSubmit)="registerUser()" class="card max-w-11/12 sm:max-w-8/12 grid md:grid-cols-2 gap-4">
<article class="space-y-4">
<form
[formGroup]="registerForm"
(ngSubmit)="registerUser()"
class="card max-w-11/12 sm:max-w-8/12 grid md:grid-cols-2 gap-4"
>
<fieldset class="fieldset">
<legend class="fieldset-legend">Name</legend>
<input type="text" class="input" formControlName="name" placeholder="Jhon Doe" />
<legend class="fieldset-legend">Name*</legend>
<input type="text" name="name" class="input" formControlName="name" placeholder="Jhon Doe" />
<app-error fieldName="name" [control]="registerForm.get('name')" />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend">Mobile Number</legend>
<input type="text" class="input" formControlName="mobile_number" placeholder="+X1 XXXXXXXXXX" />
<legend class="fieldset-legend">Mobile Number*</legend>
<input
type="text"
name="mobile_number"
class="input"
formControlName="mobile_number"
placeholder="+X1 XXXXXXXXXX"
/>
<app-error fieldName="mobile number" [control]="registerForm.get('mobile_number')" />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend">Email</legend>
<legend class="fieldset-legend">Email*</legend>
<input type="text" class="input" formControlName="email" placeholder="Enter email here" />
<p class="label">your-email-address@email.com</p>
<app-error fieldName="email" [control]="registerForm.get('email')" />
</fieldset>
</article>
<article class="space-y-4">
<fieldset class="fieldset">
<legend class="fieldset-legend">Password</legend>
<legend class="fieldset-legend">City*</legend>
<input
type="text"
name="city"
class="input"
formControlName="city"
placeholder="Your city name"
/>
<app-error fieldName="city" [control]="registerForm.get('city')" />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend">Password*</legend>
<input type="password" class="input" formControlName="password" placeholder="Type here" />
<app-error fieldName="password" [control]="registerForm.get('password')" />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend">Confirm Password</legend>
<input type="text" class="input" formControlName="password_confirmation" placeholder="Type here" />
<legend class="fieldset-legend">Confirm Password*</legend>
<input
type="text"
class="input"
formControlName="password_confirmation"
placeholder="Type here"
/>
<app-error [control]="registerForm.get('password_confirmation')" />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend">City</legend>
<input type="text" class="input" formControlName="city" placeholder="Your city name" />
</fieldset>
</article>
<div class="flex flex-col col-span-2 gap-y-2">
<button type="submit" class="btn btn-black py-2 w-full">Register</button>
<a href="" class="text-xs text-gray-800 text-center w-full block hover:text-teal-600"
<button type="submit" [disabled]="registerForm.invalid" class="btn btn-black py-2 w-full">
Register
</button>
<a
routerLink="/login"
class="text-xs text-gray-800 text-center w-full block hover:text-teal-600"
>Already have an account ? Login</a
>
</div>

View File

@ -1,30 +1,45 @@
import { Component, inject } from "@angular/core";
import { FormControl, FormGroup, ReactiveFormsModule } from "@angular/forms";
import { Component, inject, signal } from "@angular/core";
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms";
import { AuthService } from "../../services/auth-service";
import { RegisterUserRequest } from "../../../../core/models/user.model";
import { Error } from "../../../../shared/components/error/error";
import { Router, RouterLink } from "@angular/router";
@Component({
selector: "app-register",
imports: [ReactiveFormsModule],
imports: [ReactiveFormsModule, Error, RouterLink],
templateUrl: "./register.html",
styleUrl: "./register.css",
})
export class Register {
authService = inject(AuthService);
router = inject(Router);
errors = signal<string[]>([]);
registerForm = new FormGroup({
name :new FormControl(''),
email :new FormControl(''),
mobile_number : new FormControl(''),
password : new FormControl(''),
password_confirmation : new FormControl(''),
city : new FormControl(''),
name: new FormControl("", { validators: [Validators.required] }),
email: new FormControl("", { validators: [Validators.required, Validators.email] }),
mobile_number: new FormControl("", { validators: [Validators.required] }),
password: new FormControl("", { validators: [Validators.required] }),
password_confirmation: new FormControl("", { validators: [Validators.required] }),
city: new FormControl("", { validators: [Validators.required] }),
});
registerUser() {
this.authService.register(this.registerForm.value as RegisterUserRequest)
.subscribe();
// validation errors if user submit early
if (this.registerForm.invalid) {
this.registerForm.markAllAsTouched();
return;
}
this.authService.register(this.registerForm.value as RegisterUserRequest).subscribe({
next: () =>
this.router.navigate(["/login"], { state: { message: "Registration successful!" } }),
error: (error) => {
const errors: Record<number, string[]> = error?.error?.errors || {};
const errorMessages: string[] = Object.values(errors).flat();
this.errors.set(errorMessages);
},
});
}
}

View File

@ -1,8 +1,8 @@
import { TestBed } from '@angular/core/testing';
import { TestBed } from "@angular/core/testing";
import { AuthService } from './auth-service';
import { AuthService } from "./auth-service";
describe('AuthService', () => {
describe("AuthService", () => {
let service: AuthService;
beforeEach(() => {
@ -10,7 +10,7 @@ describe('AuthService', () => {
service = TestBed.inject(AuthService);
});
it('should be created', () => {
it("should be created", () => {
expect(service).toBeTruthy();
});
});

View File

@ -1,19 +1,31 @@
import { Injectable, inject } from '@angular/core';
import { RegisterUserRequest } from '../../../core/models/user.model';
import { HttpClient } from '@angular/common/http';
import { API_URL } from '../../../core/tokens/api-url-tokens';
import { Injectable, inject } from "@angular/core";
import { RegisterUserRequest } from "../../../core/models/user.model";
import { HttpClient } from "@angular/common/http";
import { API_URL, BACKEND_URL } from "../../../core/tokens/api-url-tokens";
import { switchMap } from "rxjs";
@Injectable({
providedIn: 'root',
providedIn: "root",
})
export class AuthService {
private http: HttpClient = inject(HttpClient);
private apiUrl = inject(API_URL);
private backendURL = inject(BACKEND_URL);
register(userRequest: RegisterUserRequest) {
console.log(this.apiUrl);
return this.http.post(`${this.apiUrl}/register`, userRequest);
}
login(credentials: { email: string; password: string }) {
return this.getCsrfCookie().pipe(
switchMap(() =>
this.http.post(`${this.backendURL}/login`, credentials, { observe: "response" }),
),
);
}
getCsrfCookie() {
return this.http.get(`${this.backendURL}/sanctum/csrf-cookie`);
}
}

View File

@ -0,0 +1,47 @@
import { Component, Input } from "@angular/core";
import { AbstractControl } from "@angular/forms";
import { UpperCaseFirstPipe } from "../../pipes/upper-case-first-pipe";
@Component({
selector: "app-error",
imports: [UpperCaseFirstPipe],
template: `
@if (this.control && this.control.touched) {
@for (error of getErrorMessages(); track error) {
<p class="ml-2 text-xs text-red-400">{{ error | upperCaseFirst }}</p>
}
}
`,
})
export class Error {
@Input() control!: AbstractControl | null;
@Input() fieldName = "This field";
getErrorMessages() {
const messages: string[] = [];
if (this.control && this.control.errors) {
const errors = this.control.errors;
if (errors["required"]) {
messages.push(`${this.fieldName} is required.`);
}
if (errors["email"]) {
messages.push(`Please enter a valid email address.`);
}
if (errors["minlength"]) {
messages.push(
`${this.fieldName} must be at least ${errors["minlength"].requiredLength} characters.`,
);
}
if (errors["pattern"]) {
messages.push(`${this.fieldName} is formatted incorrectly.`);
}
if (errors["serverError"]) {
messages.push(errors["serverError"]);
}
}
return messages;
}
}

View File

@ -0,0 +1,8 @@
import { UpperCaseFirstPipe } from "./upper-case-first-pipe";
describe("UpperCaseFirstPipe", () => {
it("create an instance", () => {
const pipe = new UpperCaseFirstPipe();
expect(pipe).toBeTruthy();
});
});

View File

@ -0,0 +1,10 @@
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "upperCaseFirst",
})
export class UpperCaseFirstPipe implements PipeTransform {
transform(value: string): unknown {
return value.charAt(0).toUpperCase() + value.slice(1);
}
}

View File

@ -1,4 +1,5 @@
export const environment = {
production: false,
apiUrl: 'http://localhost:8000/api',
apiUrl: "http://localhost:8000/api",
backendUrl: "http://localhost:8000",
};

View File

@ -1,4 +1,5 @@
export const environment = {
production: false,
apiUrl: 'http://my-dev-url',
apiUrl: "http://my-dev-url",
backendUrl: "http://my-dev-url",
};

View File

@ -21,7 +21,7 @@ body {
}
.btn {
@apply rounded-full transition-all duration-200 font-medium ease-out flex justify-center active:translate-y-[1px];
@apply rounded-full transition-all duration-200 font-medium ease-out flex justify-center active:translate-y-px disabled:opacity-50 disabled:cursor-not-allowed;
}
.btn-ghost {