add email verification after account registration
This commit is contained in:
@@ -36,6 +36,7 @@ dependencies {
|
|||||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
|
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-mail'
|
||||||
|
|
||||||
implementation "com.bucket4j:bucket4j-core:8.10.1"
|
implementation "com.bucket4j:bucket4j-core:8.10.1"
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ package com.krrishg;
|
|||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
|
@EnableScheduling
|
||||||
public class IndieApplication {
|
public class IndieApplication {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
|||||||
@@ -40,5 +40,11 @@ public class SchemaMigration {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Could not add ssl_email column: {}", e.getMessage());
|
log.warn("Could not add ssl_email column: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
jdbcTemplate.execute("ALTER TABLE users DROP CONSTRAINT IF EXISTS users_provider_check");
|
||||||
|
log.info("Dropped provider check constraint from users");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Could not drop provider check constraint: {}", e.getMessage());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,11 @@ import com.krrishg.dto.AuthResponse;
|
|||||||
import com.krrishg.dto.LoginRequest;
|
import com.krrishg.dto.LoginRequest;
|
||||||
import com.krrishg.dto.RefreshTokenRequest;
|
import com.krrishg.dto.RefreshTokenRequest;
|
||||||
import com.krrishg.dto.RegisterRequest;
|
import com.krrishg.dto.RegisterRequest;
|
||||||
|
import com.krrishg.dto.RegistrationResponse;
|
||||||
|
import com.krrishg.dto.ResendVerificationRequest;
|
||||||
|
import com.krrishg.dto.SetPasswordRequest;
|
||||||
|
import com.krrishg.dto.VerifyEmailRequest;
|
||||||
|
import com.krrishg.dto.VerifyEmailResponse;
|
||||||
import com.krrishg.service.AuthService;
|
import com.krrishg.service.AuthService;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
@@ -24,8 +29,8 @@ public class AuthController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/register")
|
@PostMapping("/register")
|
||||||
public ResponseEntity<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
|
public ResponseEntity<RegistrationResponse> register(@Valid @RequestBody RegisterRequest request) {
|
||||||
AuthResponse response = authService.register(request);
|
RegistrationResponse response = authService.register(request);
|
||||||
return ResponseEntity.status(HttpStatus.CREATED).body(response);
|
return ResponseEntity.status(HttpStatus.CREATED).body(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,4 +50,22 @@ public class AuthController {
|
|||||||
public ResponseEntity<Void> logout() {
|
public ResponseEntity<Void> logout() {
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/verify-email")
|
||||||
|
public ResponseEntity<VerifyEmailResponse> verifyEmail(@Valid @RequestBody VerifyEmailRequest request) {
|
||||||
|
VerifyEmailResponse response = authService.verifyEmail(request);
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/resend-verification")
|
||||||
|
public ResponseEntity<RegistrationResponse> resendVerification(@Valid @RequestBody ResendVerificationRequest request) {
|
||||||
|
RegistrationResponse response = authService.resendVerification(request);
|
||||||
|
return ResponseEntity.ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/set-password")
|
||||||
|
public ResponseEntity<Void> setPassword(@Valid @RequestBody SetPasswordRequest request) {
|
||||||
|
authService.setPassword(request);
|
||||||
|
return ResponseEntity.ok().build();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.krrishg.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public class RegistrationResponse {
|
||||||
|
private String message;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.krrishg.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.Email;
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class ResendVerificationRequest {
|
||||||
|
@NotBlank
|
||||||
|
@Email
|
||||||
|
private String email;
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.krrishg.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SetPasswordRequest {
|
||||||
|
@NotBlank
|
||||||
|
private String setupToken;
|
||||||
|
|
||||||
|
@NotBlank
|
||||||
|
@Size(min = 8, max = 100)
|
||||||
|
private String password;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.krrishg.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class VerifyEmailRequest {
|
||||||
|
@NotBlank
|
||||||
|
private String token;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.krrishg.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public class VerifyEmailResponse {
|
||||||
|
private String message;
|
||||||
|
private String setupToken;
|
||||||
|
}
|
||||||
@@ -39,6 +39,14 @@ public class User {
|
|||||||
@Builder.Default
|
@Builder.Default
|
||||||
private boolean emailVerified = false;
|
private boolean emailVerified = false;
|
||||||
|
|
||||||
|
@Enumerated(EnumType.STRING)
|
||||||
|
@Column(name = "provider", nullable = false)
|
||||||
|
@Builder.Default
|
||||||
|
private AuthProvider provider = AuthProvider.LOCAL;
|
||||||
|
|
||||||
|
@Column(name = "provider_id")
|
||||||
|
private String providerId;
|
||||||
|
|
||||||
@Convert(converter = MapToJsonConverter.class)
|
@Convert(converter = MapToJsonConverter.class)
|
||||||
@Column(name = "llm_api_keys", columnDefinition = "TEXT")
|
@Column(name = "llm_api_keys", columnDefinition = "TEXT")
|
||||||
private Map<String, String> llmApiKeys;
|
private Map<String, String> llmApiKeys;
|
||||||
@@ -58,7 +66,7 @@ public class User {
|
|||||||
private LocalDateTime updatedAt;
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
void onCreate() {
|
public void onCreate() {
|
||||||
if (id == null) {
|
if (id == null) {
|
||||||
id = UUID.randomUUID();
|
id = UUID.randomUUID();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package com.krrishg.model;
|
||||||
|
|
||||||
|
import jakarta.persistence.Column;
|
||||||
|
import jakarta.persistence.Entity;
|
||||||
|
import jakarta.persistence.Id;
|
||||||
|
import jakarta.persistence.PrePersist;
|
||||||
|
import jakarta.persistence.Table;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Table(name = "verification_tokens")
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public class VerificationToken {
|
||||||
|
|
||||||
|
@Id
|
||||||
|
@Column(name = "id")
|
||||||
|
private UUID id;
|
||||||
|
|
||||||
|
@Column(name = "user_id", nullable = false)
|
||||||
|
private UUID userId;
|
||||||
|
|
||||||
|
@Column(name = "token", nullable = false, unique = true)
|
||||||
|
private String token;
|
||||||
|
|
||||||
|
@Column(name = "setup_token")
|
||||||
|
private String setupToken;
|
||||||
|
|
||||||
|
@Column(name = "setup_token_used")
|
||||||
|
@Builder.Default
|
||||||
|
private boolean setupTokenUsed = false;
|
||||||
|
|
||||||
|
@Column(name = "expiry_date", nullable = false)
|
||||||
|
private LocalDateTime expiryDate;
|
||||||
|
|
||||||
|
@Column(name = "used")
|
||||||
|
@Builder.Default
|
||||||
|
private boolean used = false;
|
||||||
|
|
||||||
|
@Column(name = "created_at", nullable = false, updatable = false)
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
@PrePersist
|
||||||
|
public void onCreate() {
|
||||||
|
if (id == null) {
|
||||||
|
id = UUID.randomUUID();
|
||||||
|
}
|
||||||
|
createdAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.krrishg.repository;
|
||||||
|
|
||||||
|
import com.krrishg.model.VerificationToken;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public interface VerificationTokenRepository extends JpaRepository<VerificationToken, UUID> {
|
||||||
|
|
||||||
|
Optional<VerificationToken> findByToken(String token);
|
||||||
|
|
||||||
|
Optional<VerificationToken> findBySetupToken(String setupToken);
|
||||||
|
|
||||||
|
void deleteByUserId(UUID userId);
|
||||||
|
|
||||||
|
List<VerificationToken> findByUsedFalseAndExpiryDateBefore(LocalDateTime now);
|
||||||
|
}
|
||||||
@@ -4,31 +4,67 @@ import com.krrishg.config.TokenService;
|
|||||||
import com.krrishg.dto.AuthResponse;
|
import com.krrishg.dto.AuthResponse;
|
||||||
import com.krrishg.dto.LoginRequest;
|
import com.krrishg.dto.LoginRequest;
|
||||||
import com.krrishg.dto.RefreshTokenRequest;
|
import com.krrishg.dto.RefreshTokenRequest;
|
||||||
|
import com.krrishg.dto.RegistrationResponse;
|
||||||
import com.krrishg.dto.RegisterRequest;
|
import com.krrishg.dto.RegisterRequest;
|
||||||
|
import com.krrishg.dto.ResendVerificationRequest;
|
||||||
|
import com.krrishg.dto.SetPasswordRequest;
|
||||||
|
import com.krrishg.dto.VerifyEmailRequest;
|
||||||
|
import com.krrishg.dto.VerifyEmailResponse;
|
||||||
import com.krrishg.model.User;
|
import com.krrishg.model.User;
|
||||||
|
import com.krrishg.model.VerificationToken;
|
||||||
import com.krrishg.repository.UserRepository;
|
import com.krrishg.repository.UserRepository;
|
||||||
|
import com.krrishg.repository.VerificationTokenRepository;
|
||||||
import io.jsonwebtoken.Claims;
|
import io.jsonwebtoken.Claims;
|
||||||
import lombok.RequiredArgsConstructor;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class AuthService {
|
public class AuthService {
|
||||||
|
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
private final TokenService jwtConfig;
|
private final TokenService jwtConfig;
|
||||||
|
private final VerificationTokenRepository verificationTokenRepository;
|
||||||
|
private final EmailService emailService;
|
||||||
|
private final int tokenExpirationMinutes;
|
||||||
|
|
||||||
|
public AuthService(UserRepository userRepository,
|
||||||
|
PasswordEncoder passwordEncoder,
|
||||||
|
TokenService jwtConfig,
|
||||||
|
VerificationTokenRepository verificationTokenRepository,
|
||||||
|
EmailService emailService,
|
||||||
|
@Value("${indie.app.verification-token-expiration-minutes}") int tokenExpirationMinutes) {
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
this.jwtConfig = jwtConfig;
|
||||||
|
this.verificationTokenRepository = verificationTokenRepository;
|
||||||
|
this.emailService = emailService;
|
||||||
|
this.tokenExpirationMinutes = tokenExpirationMinutes;
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public AuthResponse register(RegisterRequest request) {
|
public RegistrationResponse register(RegisterRequest request) {
|
||||||
String email = request.getEmail().toLowerCase().strip();
|
String email = request.getEmail().toLowerCase().strip();
|
||||||
|
|
||||||
if (userRepository.existsByEmail(email)) {
|
Optional<User> existingUser = userRepository.findByEmail(email);
|
||||||
throw new IllegalArgumentException("Email already registered");
|
|
||||||
|
if (existingUser.isPresent()) {
|
||||||
|
if (existingUser.get().isEmailVerified()) {
|
||||||
|
return new RegistrationResponse("If this email is available, a verification link has been sent.");
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = existingUser.get();
|
||||||
|
verificationTokenRepository.deleteByUserId(user.getId());
|
||||||
|
VerificationToken token = createVerificationToken(user.getId());
|
||||||
|
verificationTokenRepository.save(token);
|
||||||
|
emailService.sendVerificationEmail(user.getEmail(), user.getName(), token.getToken());
|
||||||
|
return new RegistrationResponse("If this email is available, a verification link has been sent.");
|
||||||
}
|
}
|
||||||
|
|
||||||
User user = User.builder()
|
User user = User.builder()
|
||||||
@@ -39,7 +75,12 @@ public class AuthService {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
user = userRepository.save(user);
|
user = userRepository.save(user);
|
||||||
return generateAuthResponse(user);
|
|
||||||
|
VerificationToken token = createVerificationToken(user.getId());
|
||||||
|
verificationTokenRepository.save(token);
|
||||||
|
emailService.sendVerificationEmail(user.getEmail(), user.getName(), token.getToken());
|
||||||
|
|
||||||
|
return new RegistrationResponse("If this email is available, a verification link has been sent.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public AuthResponse login(LoginRequest request) {
|
public AuthResponse login(LoginRequest request) {
|
||||||
@@ -51,9 +92,95 @@ public class AuthService {
|
|||||||
throw new IllegalArgumentException("Invalid email or password");
|
throw new IllegalArgumentException("Invalid email or password");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!user.isEmailVerified()) {
|
||||||
|
throw new IllegalArgumentException("Please verify your email address before logging in");
|
||||||
|
}
|
||||||
|
|
||||||
return generateAuthResponse(user);
|
return generateAuthResponse(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public VerifyEmailResponse verifyEmail(VerifyEmailRequest request) {
|
||||||
|
VerificationToken token = verificationTokenRepository.findByToken(request.getToken())
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Invalid verification token"));
|
||||||
|
|
||||||
|
if (token.isUsed()) {
|
||||||
|
throw new IllegalArgumentException("Verification token has already been used");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.getExpiryDate().isBefore(LocalDateTime.now())) {
|
||||||
|
throw new IllegalArgumentException("Verification token has expired");
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = userRepository.findById(token.getUserId())
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("User not found"));
|
||||||
|
|
||||||
|
user.setEmailVerified(true);
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
token.setUsed(true);
|
||||||
|
String setupToken = UUID.randomUUID().toString();
|
||||||
|
token.setSetupToken(setupToken);
|
||||||
|
token.setSetupTokenUsed(false);
|
||||||
|
verificationTokenRepository.save(token);
|
||||||
|
|
||||||
|
return VerifyEmailResponse.builder()
|
||||||
|
.message("Email verified successfully")
|
||||||
|
.setupToken(setupToken)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public RegistrationResponse resendVerification(ResendVerificationRequest request) {
|
||||||
|
String email = request.getEmail().toLowerCase().strip();
|
||||||
|
|
||||||
|
Optional<User> existingUser = userRepository.findByEmail(email);
|
||||||
|
|
||||||
|
if (existingUser.isEmpty()) {
|
||||||
|
return new RegistrationResponse("If this email is available, a verification link has been sent.");
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = existingUser.get();
|
||||||
|
|
||||||
|
if (user.isEmailVerified()) {
|
||||||
|
return new RegistrationResponse("If this email is available, a verification link has been sent.");
|
||||||
|
}
|
||||||
|
|
||||||
|
verificationTokenRepository.deleteByUserId(user.getId());
|
||||||
|
VerificationToken token = createVerificationToken(user.getId());
|
||||||
|
verificationTokenRepository.save(token);
|
||||||
|
emailService.sendVerificationEmail(user.getEmail(), user.getName(), token.getToken());
|
||||||
|
|
||||||
|
return new RegistrationResponse("If this email is available, a verification link has been sent.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void setPassword(SetPasswordRequest request) {
|
||||||
|
VerificationToken token = verificationTokenRepository.findBySetupToken(request.getSetupToken())
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("Invalid setup token"));
|
||||||
|
|
||||||
|
if (!token.isUsed()) {
|
||||||
|
throw new IllegalArgumentException("Email must be verified first");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.isSetupTokenUsed()) {
|
||||||
|
throw new IllegalArgumentException("Setup token has already been used");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token.getExpiryDate().isBefore(LocalDateTime.now())) {
|
||||||
|
throw new IllegalArgumentException("Setup token has expired");
|
||||||
|
}
|
||||||
|
|
||||||
|
User user = userRepository.findById(token.getUserId())
|
||||||
|
.orElseThrow(() -> new IllegalArgumentException("User not found"));
|
||||||
|
|
||||||
|
user.setPassword(passwordEncoder.encode(request.getPassword()));
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
token.setSetupTokenUsed(true);
|
||||||
|
verificationTokenRepository.save(token);
|
||||||
|
}
|
||||||
|
|
||||||
public AuthResponse refreshToken(RefreshTokenRequest request) {
|
public AuthResponse refreshToken(RefreshTokenRequest request) {
|
||||||
try {
|
try {
|
||||||
Claims claims = jwtConfig.validateToken(request.getRefreshToken());
|
Claims claims = jwtConfig.validateToken(request.getRefreshToken());
|
||||||
@@ -68,6 +195,15 @@ public class AuthService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private VerificationToken createVerificationToken(UUID userId) {
|
||||||
|
return VerificationToken.builder()
|
||||||
|
.userId(userId)
|
||||||
|
.token(UUID.randomUUID().toString())
|
||||||
|
.expiryDate(LocalDateTime.now().plusMinutes(tokenExpirationMinutes))
|
||||||
|
.used(false)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
private AuthResponse generateAuthResponse(User user) {
|
private AuthResponse generateAuthResponse(User user) {
|
||||||
String accessToken = jwtConfig.generateAccessToken(user);
|
String accessToken = jwtConfig.generateAccessToken(user);
|
||||||
String refreshToken = jwtConfig.generateRefreshToken(user);
|
String refreshToken = jwtConfig.generateRefreshToken(user);
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package com.krrishg.service;
|
||||||
|
|
||||||
|
import com.krrishg.model.VerificationToken;
|
||||||
|
import com.krrishg.repository.UserRepository;
|
||||||
|
import com.krrishg.repository.VerificationTokenRepository;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class CleanupService {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(CleanupService.class);
|
||||||
|
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
private final VerificationTokenRepository verificationTokenRepository;
|
||||||
|
|
||||||
|
public CleanupService(UserRepository userRepository,
|
||||||
|
VerificationTokenRepository verificationTokenRepository) {
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
this.verificationTokenRepository = verificationTokenRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Scheduled(cron = "0 0 */6 * * ?")
|
||||||
|
@Transactional
|
||||||
|
public void cleanupStaleUnverifiedAccounts() {
|
||||||
|
LocalDateTime cutoff = LocalDateTime.now().minusHours(24);
|
||||||
|
List<VerificationToken> staleTokens = verificationTokenRepository
|
||||||
|
.findByUsedFalseAndExpiryDateBefore(cutoff);
|
||||||
|
|
||||||
|
if (staleTokens.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<UUID> userIds = staleTokens.stream()
|
||||||
|
.map(VerificationToken::getUserId)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
for (UUID userId : userIds) {
|
||||||
|
userRepository.findById(userId).ifPresent(user -> {
|
||||||
|
if (!user.isEmailVerified()) {
|
||||||
|
userRepository.delete(user);
|
||||||
|
verificationTokenRepository.deleteByUserId(userId);
|
||||||
|
log.info("Cleaned up unverified account: {} ({})", user.getEmail(), userId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
80
backend/src/main/java/com/krrishg/service/EmailService.java
Normal file
80
backend/src/main/java/com/krrishg/service/EmailService.java
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
package com.krrishg.service;
|
||||||
|
|
||||||
|
import jakarta.mail.MessagingException;
|
||||||
|
import jakarta.mail.internet.MimeMessage;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.mail.javamail.JavaMailSender;
|
||||||
|
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class EmailService {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(EmailService.class);
|
||||||
|
|
||||||
|
private final JavaMailSender mailSender;
|
||||||
|
private final String baseUrl;
|
||||||
|
|
||||||
|
public EmailService(JavaMailSender mailSender,
|
||||||
|
@Value("${indie.app.base-url}") String baseUrl) {
|
||||||
|
this.mailSender = mailSender;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void sendVerificationEmail(String to, String name, String token) {
|
||||||
|
String link = baseUrl + "/verify-email?token=" + token;
|
||||||
|
String subject = "Verify your Indie account";
|
||||||
|
String html = """
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head><meta charset="utf-8"></head>
|
||||||
|
<body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 0; background-color: #f9fafb;">
|
||||||
|
<table width="100%%" cellpadding="0" cellspacing="0" style="padding: 40px 20px;">
|
||||||
|
<tr><td align="center">
|
||||||
|
<table width="480" cellpadding="0" cellspacing="0" style="background: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
|
||||||
|
<tr><td style="padding: 40px 32px 24px; text-align: center;">
|
||||||
|
<h1 style="margin: 0; font-size: 32px; color: #4f46e5;">Indie</h1>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="padding: 0 32px 16px;">
|
||||||
|
<p style="margin: 0 0 8px; font-size: 16px; color: #374151;">Hi %s,</p>
|
||||||
|
<p style="margin: 0 0 24px; font-size: 16px; color: #374151; line-height: 1.5;">
|
||||||
|
Someone created an account with this email address. If this was you, click the button below to verify your email and set your password.
|
||||||
|
</p>
|
||||||
|
<table cellpadding="0" cellspacing="0" style="margin: 0 auto 24px;">
|
||||||
|
<tr><td align="center" style="background: #4f46e5; border-radius: 8px; padding: 12px 32px;">
|
||||||
|
<a href="%s" style="color: #ffffff; font-size: 16px; font-weight: 600; text-decoration: none; display: inline-block;">Verify Email Address</a>
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
<p style="margin: 0 0 8px; font-size: 14px; color: #9ca3af;">This link expires in 24 hours.</p>
|
||||||
|
<p style="margin: 0; font-size: 14px; color: #9ca3af;">If you didn't create this account, you can safely ignore this email.</p>
|
||||||
|
</td></tr>
|
||||||
|
<tr><td style="padding: 24px 32px; background: #f9fafb; border-top: 1px solid #e5e7eb;">
|
||||||
|
<p style="margin: 0; font-size: 12px; color: #9ca3af; text-align: center;">Indie Platform</p>
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
""".formatted(name, link);
|
||||||
|
|
||||||
|
sendHtml(to, subject, html);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendHtml(String to, String subject, String html) {
|
||||||
|
try {
|
||||||
|
MimeMessage message = mailSender.createMimeMessage();
|
||||||
|
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
|
||||||
|
helper.setTo(to);
|
||||||
|
helper.setSubject(subject);
|
||||||
|
helper.setText(html, true);
|
||||||
|
mailSender.send(message);
|
||||||
|
log.info("Verification email sent to {}", to);
|
||||||
|
} catch (MessagingException e) {
|
||||||
|
log.error("Failed to send verification email to {}", to, e);
|
||||||
|
throw new RuntimeException("Failed to send verification email", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,6 +26,18 @@ spring:
|
|||||||
show-sql: true
|
show-sql: true
|
||||||
open-in-view: false
|
open-in-view: false
|
||||||
|
|
||||||
|
mail:
|
||||||
|
host: ${EMAIL_HOST:localhost}
|
||||||
|
port: ${EMAIL_PORT:1025}
|
||||||
|
username: ${EMAIL_USERNAME:}
|
||||||
|
password: ${EMAIL_PASSWORD:}
|
||||||
|
properties:
|
||||||
|
mail:
|
||||||
|
smtp:
|
||||||
|
auth: ${EMAIL_SMTP_AUTH:true}
|
||||||
|
starttls:
|
||||||
|
enable: ${EMAIL_SMTP_STARTTLS:true}
|
||||||
|
|
||||||
springdoc:
|
springdoc:
|
||||||
api-docs:
|
api-docs:
|
||||||
path: /api-docs
|
path: /api-docs
|
||||||
@@ -57,6 +69,10 @@ indie:
|
|||||||
encryption:
|
encryption:
|
||||||
master-key-path: ${INDIE_ENCRYPTION_KEY_PATH:config/encryption.key}
|
master-key-path: ${INDIE_ENCRYPTION_KEY_PATH:config/encryption.key}
|
||||||
|
|
||||||
|
app:
|
||||||
|
base-url: ${INDIE_APP_BASE_URL:http://localhost:4200}
|
||||||
|
verification-token-expiration-minutes: ${INDIE_VERIFICATION_TOKEN_EXPIRATION:1440}
|
||||||
|
|
||||||
llm:
|
llm:
|
||||||
rate-limit:
|
rate-limit:
|
||||||
max-requests-per-hour: ${INDIE_LLM_RATE_LIMIT:10}
|
max-requests-per-hour: ${INDIE_LLM_RATE_LIMIT:10}
|
||||||
|
|||||||
@@ -6,6 +6,11 @@ import com.krrishg.dto.AuthResponse.UserInfo;
|
|||||||
import com.krrishg.dto.LoginRequest;
|
import com.krrishg.dto.LoginRequest;
|
||||||
import com.krrishg.dto.RefreshTokenRequest;
|
import com.krrishg.dto.RefreshTokenRequest;
|
||||||
import com.krrishg.dto.RegisterRequest;
|
import com.krrishg.dto.RegisterRequest;
|
||||||
|
import com.krrishg.dto.RegistrationResponse;
|
||||||
|
import com.krrishg.dto.ResendVerificationRequest;
|
||||||
|
import com.krrishg.dto.SetPasswordRequest;
|
||||||
|
import com.krrishg.dto.VerifyEmailRequest;
|
||||||
|
import com.krrishg.dto.VerifyEmailResponse;
|
||||||
import com.krrishg.service.AuthService;
|
import com.krrishg.service.AuthService;
|
||||||
import com.krrishg.support.TestSecurityConfig;
|
import com.krrishg.support.TestSecurityConfig;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
@@ -20,6 +25,7 @@ import org.springframework.test.web.servlet.MockMvc;
|
|||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.doThrow;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||||
@@ -40,14 +46,9 @@ class AuthControllerTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void registerReturns201() throws Exception {
|
void registerReturns201WithMessage() throws Exception {
|
||||||
AuthResponse response = AuthResponse.builder()
|
when(authService.register(any(RegisterRequest.class)))
|
||||||
.accessToken("at-123")
|
.thenReturn(new RegistrationResponse("If this email is available, a verification link has been sent."));
|
||||||
.refreshToken("rt-456")
|
|
||||||
.tokenType("Bearer")
|
|
||||||
.user(new UserInfo(UUID.randomUUID(), "test@example.com", "Test", null))
|
|
||||||
.build();
|
|
||||||
when(authService.register(any(RegisterRequest.class))).thenReturn(response);
|
|
||||||
|
|
||||||
RegisterRequest request = new RegisterRequest();
|
RegisterRequest request = new RegisterRequest();
|
||||||
request.setEmail("test@example.com");
|
request.setEmail("test@example.com");
|
||||||
@@ -58,10 +59,7 @@ class AuthControllerTest {
|
|||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
.content(objectMapper.writeValueAsString(request)))
|
.content(objectMapper.writeValueAsString(request)))
|
||||||
.andExpect(status().isCreated())
|
.andExpect(status().isCreated())
|
||||||
.andExpect(jsonPath("$.accessToken").value("at-123"))
|
.andExpect(jsonPath("$.message").value("If this email is available, a verification link has been sent."));
|
||||||
.andExpect(jsonPath("$.refreshToken").value("rt-456"))
|
|
||||||
.andExpect(jsonPath("$.tokenType").value("Bearer"))
|
|
||||||
.andExpect(jsonPath("$.user.email").value("test@example.com"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -112,6 +110,22 @@ class AuthControllerTest {
|
|||||||
.andExpect(jsonPath("$.detail").value("Invalid email or password"));
|
.andExpect(jsonPath("$.detail").value("Invalid email or password"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void loginReturns400OnUnverifiedEmail() throws Exception {
|
||||||
|
when(authService.login(any(LoginRequest.class)))
|
||||||
|
.thenThrow(new IllegalArgumentException("Please verify your email address before logging in"));
|
||||||
|
|
||||||
|
LoginRequest request = new LoginRequest();
|
||||||
|
request.setEmail("unverified@example.com");
|
||||||
|
request.setPassword("password123");
|
||||||
|
|
||||||
|
mockMvc.perform(post("/api/auth/login")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(objectMapper.writeValueAsString(request)))
|
||||||
|
.andExpect(status().isBadRequest())
|
||||||
|
.andExpect(jsonPath("$.detail").value("Please verify your email address before logging in"));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void refreshReturns200() throws Exception {
|
void refreshReturns200() throws Exception {
|
||||||
AuthResponse response = AuthResponse.builder()
|
AuthResponse response = AuthResponse.builder()
|
||||||
@@ -137,4 +151,93 @@ class AuthControllerTest {
|
|||||||
mockMvc.perform(post("/api/auth/logout"))
|
mockMvc.perform(post("/api/auth/logout"))
|
||||||
.andExpect(status().isNoContent());
|
.andExpect(status().isNoContent());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyEmailReturns200() throws Exception {
|
||||||
|
when(authService.verifyEmail(any(VerifyEmailRequest.class)))
|
||||||
|
.thenReturn(new VerifyEmailResponse("Email verified successfully", "setup-token-123"));
|
||||||
|
|
||||||
|
VerifyEmailRequest request = new VerifyEmailRequest();
|
||||||
|
request.setToken("valid-token");
|
||||||
|
|
||||||
|
mockMvc.perform(post("/api/auth/verify-email")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(objectMapper.writeValueAsString(request)))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.message").value("Email verified successfully"))
|
||||||
|
.andExpect(jsonPath("$.setupToken").value("setup-token-123"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyEmailReturns400OnInvalidToken() throws Exception {
|
||||||
|
when(authService.verifyEmail(any(VerifyEmailRequest.class)))
|
||||||
|
.thenThrow(new IllegalArgumentException("Invalid verification token"));
|
||||||
|
|
||||||
|
VerifyEmailRequest request = new VerifyEmailRequest();
|
||||||
|
request.setToken("bad-token");
|
||||||
|
|
||||||
|
mockMvc.perform(post("/api/auth/verify-email")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(objectMapper.writeValueAsString(request)))
|
||||||
|
.andExpect(status().isBadRequest())
|
||||||
|
.andExpect(jsonPath("$.detail").value("Invalid verification token"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyEmailReturns400OnExpiredToken() throws Exception {
|
||||||
|
when(authService.verifyEmail(any(VerifyEmailRequest.class)))
|
||||||
|
.thenThrow(new IllegalArgumentException("Verification token has expired"));
|
||||||
|
|
||||||
|
VerifyEmailRequest request = new VerifyEmailRequest();
|
||||||
|
request.setToken("expired-token");
|
||||||
|
|
||||||
|
mockMvc.perform(post("/api/auth/verify-email")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(objectMapper.writeValueAsString(request)))
|
||||||
|
.andExpect(status().isBadRequest())
|
||||||
|
.andExpect(jsonPath("$.detail").value("Verification token has expired"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resendVerificationReturns200() throws Exception {
|
||||||
|
when(authService.resendVerification(any(ResendVerificationRequest.class)))
|
||||||
|
.thenReturn(new RegistrationResponse("If this email is available, a verification link has been sent."));
|
||||||
|
|
||||||
|
ResendVerificationRequest request = new ResendVerificationRequest();
|
||||||
|
request.setEmail("user@example.com");
|
||||||
|
|
||||||
|
mockMvc.perform(post("/api/auth/resend-verification")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(objectMapper.writeValueAsString(request)))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.message").value("If this email is available, a verification link has been sent."));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setPasswordReturns200() throws Exception {
|
||||||
|
SetPasswordRequest request = new SetPasswordRequest();
|
||||||
|
request.setSetupToken("setup-token-123");
|
||||||
|
request.setPassword("new-password");
|
||||||
|
|
||||||
|
mockMvc.perform(post("/api/auth/set-password")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(objectMapper.writeValueAsString(request)))
|
||||||
|
.andExpect(status().isOk());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setPasswordReturns400OnInvalidToken() throws Exception {
|
||||||
|
doThrow(new IllegalArgumentException("Invalid setup token"))
|
||||||
|
.when(authService).setPassword(any(SetPasswordRequest.class));
|
||||||
|
|
||||||
|
SetPasswordRequest request = new SetPasswordRequest();
|
||||||
|
request.setSetupToken("bad-token");
|
||||||
|
request.setPassword("new-password");
|
||||||
|
|
||||||
|
mockMvc.perform(post("/api/auth/set-password")
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.content(objectMapper.writeValueAsString(request)))
|
||||||
|
.andExpect(status().isBadRequest())
|
||||||
|
.andExpect(jsonPath("$.detail").value("Invalid setup token"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,5 +63,6 @@ class UserTest {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
assertFalse(user.isEmailVerified());
|
assertFalse(user.isEmailVerified());
|
||||||
|
assertEquals(AuthProvider.LOCAL, user.getProvider());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,58 +4,110 @@ import com.krrishg.dto.AuthResponse;
|
|||||||
import com.krrishg.dto.LoginRequest;
|
import com.krrishg.dto.LoginRequest;
|
||||||
import com.krrishg.dto.RefreshTokenRequest;
|
import com.krrishg.dto.RefreshTokenRequest;
|
||||||
import com.krrishg.dto.RegisterRequest;
|
import com.krrishg.dto.RegisterRequest;
|
||||||
|
import com.krrishg.dto.RegistrationResponse;
|
||||||
|
import com.krrishg.dto.ResendVerificationRequest;
|
||||||
|
import com.krrishg.dto.SetPasswordRequest;
|
||||||
|
import com.krrishg.dto.VerifyEmailRequest;
|
||||||
|
import com.krrishg.dto.VerifyEmailResponse;
|
||||||
import com.krrishg.model.User;
|
import com.krrishg.model.User;
|
||||||
|
import com.krrishg.model.VerificationToken;
|
||||||
import com.krrishg.support.FakeJwtConfig;
|
import com.krrishg.support.FakeJwtConfig;
|
||||||
import com.krrishg.support.FakeUserRepository;
|
import com.krrishg.support.FakeUserRepository;
|
||||||
|
import com.krrishg.support.FakeVerificationTokenRepository;
|
||||||
|
import com.krrishg.support.StubEmailService;
|
||||||
import com.krrishg.support.StubPasswordEncoder;
|
import com.krrishg.support.StubPasswordEncoder;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
class AuthServiceTest {
|
class AuthServiceTest {
|
||||||
|
|
||||||
private FakeUserRepository userRepository;
|
private FakeUserRepository userRepository;
|
||||||
|
private FakeVerificationTokenRepository tokenRepository;
|
||||||
|
private StubEmailService emailService;
|
||||||
private AuthService authService;
|
private AuthService authService;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
userRepository = new FakeUserRepository();
|
userRepository = new FakeUserRepository();
|
||||||
authService = new AuthService(userRepository, new StubPasswordEncoder(), new FakeJwtConfig());
|
tokenRepository = new FakeVerificationTokenRepository();
|
||||||
|
emailService = new StubEmailService();
|
||||||
|
authService = new AuthService(userRepository, new StubPasswordEncoder(),
|
||||||
|
new FakeJwtConfig(), tokenRepository, emailService, 1440);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void registerCreatesUserAndReturnsTokens() {
|
void registerCreatesUserAndSendsVerification() {
|
||||||
RegisterRequest request = new RegisterRequest();
|
RegisterRequest request = new RegisterRequest();
|
||||||
request.setEmail("new@example.com");
|
request.setEmail("new@example.com");
|
||||||
request.setPassword("password123");
|
request.setPassword("password123");
|
||||||
request.setName("New User");
|
request.setName("New User");
|
||||||
|
|
||||||
AuthResponse response = authService.register(request);
|
RegistrationResponse response = authService.register(request);
|
||||||
|
|
||||||
assertNotNull(response.getAccessToken());
|
assertEquals("If this email is available, a verification link has been sent.", response.getMessage());
|
||||||
assertNotNull(response.getRefreshToken());
|
assertTrue(userRepository.findByEmail("new@example.com").isPresent());
|
||||||
assertEquals("Bearer", response.getTokenType());
|
assertFalse(userRepository.findByEmail("new@example.com").get().isEmailVerified());
|
||||||
assertEquals("new@example.com", response.getUser().getEmail());
|
|
||||||
assertEquals("New User", response.getUser().getName());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void registerThrowsOnDuplicateEmail() {
|
void registerSendsVerificationEmail() {
|
||||||
RegisterRequest request = new RegisterRequest();
|
RegisterRequest request = new RegisterRequest();
|
||||||
request.setEmail("dup@example.com");
|
request.setEmail("emailtest@example.com");
|
||||||
request.setPassword("password123");
|
request.setPassword("password123");
|
||||||
request.setName("User");
|
request.setName("Email Test");
|
||||||
|
|
||||||
authService.register(request);
|
authService.register(request);
|
||||||
|
|
||||||
RegisterRequest duplicate = new RegisterRequest();
|
assertEquals("emailtest@example.com", emailService.getLastTo());
|
||||||
duplicate.setEmail("dup@example.com");
|
assertNotNull(emailService.getLastToken());
|
||||||
duplicate.setPassword("password456");
|
assertEquals(1, emailService.getSendCount());
|
||||||
duplicate.setName("Other");
|
}
|
||||||
|
|
||||||
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
@Test
|
||||||
() -> authService.register(duplicate));
|
void registerReturnsGenericMessageForExistingVerifiedEmail() {
|
||||||
assertEquals("Email already registered", ex.getMessage());
|
User user = User.builder()
|
||||||
|
.email("verified@example.com")
|
||||||
|
.name("Verified")
|
||||||
|
.emailVerified(true)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
RegisterRequest request = new RegisterRequest();
|
||||||
|
request.setEmail("verified@example.com");
|
||||||
|
request.setPassword("password123");
|
||||||
|
request.setName("Should Not Matter");
|
||||||
|
|
||||||
|
RegistrationResponse response = authService.register(request);
|
||||||
|
|
||||||
|
assertEquals("If this email is available, a verification link has been sent.", response.getMessage());
|
||||||
|
assertEquals(0, emailService.getSendCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void registerResendsForExistingUnverifiedEmail() {
|
||||||
|
User user = User.builder()
|
||||||
|
.email("unverified@example.com")
|
||||||
|
.name("Unverified")
|
||||||
|
.emailVerified(false)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
RegisterRequest request = new RegisterRequest();
|
||||||
|
request.setEmail("unverified@example.com");
|
||||||
|
request.setPassword("newpassword");
|
||||||
|
request.setName("New Name");
|
||||||
|
|
||||||
|
RegistrationResponse response = authService.register(request);
|
||||||
|
|
||||||
|
assertEquals("If this email is available, a verification link has been sent.", response.getMessage());
|
||||||
|
assertEquals(1, emailService.getSendCount());
|
||||||
|
assertEquals("unverified@example.com", emailService.getLastTo());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -65,19 +117,23 @@ class AuthServiceTest {
|
|||||||
request.setPassword("password123");
|
request.setPassword("password123");
|
||||||
request.setName("User");
|
request.setName("User");
|
||||||
|
|
||||||
AuthResponse response = authService.register(request);
|
authService.register(request);
|
||||||
|
|
||||||
assertEquals("uppercase@example.com", response.getUser().getEmail());
|
assertTrue(userRepository.findByEmail("uppercase@example.com").isPresent());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void loginWithValidCredentialsReturnsTokens() {
|
void loginWithValidCredentialsAndVerifiedEmailReturnsTokens() {
|
||||||
RegisterRequest reg = new RegisterRequest();
|
RegisterRequest reg = new RegisterRequest();
|
||||||
reg.setEmail("login@example.com");
|
reg.setEmail("login@example.com");
|
||||||
reg.setPassword("password123");
|
reg.setPassword("password123");
|
||||||
reg.setName("Login User");
|
reg.setName("Login User");
|
||||||
authService.register(reg);
|
authService.register(reg);
|
||||||
|
|
||||||
|
User user = userRepository.findByEmail("login@example.com").get();
|
||||||
|
user.setEmailVerified(true);
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
LoginRequest login = new LoginRequest();
|
LoginRequest login = new LoginRequest();
|
||||||
login.setEmail("login@example.com");
|
login.setEmail("login@example.com");
|
||||||
login.setPassword("password123");
|
login.setPassword("password123");
|
||||||
@@ -89,6 +145,23 @@ class AuthServiceTest {
|
|||||||
assertEquals("login@example.com", response.getUser().getEmail());
|
assertEquals("login@example.com", response.getUser().getEmail());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void loginThrowsWhenEmailNotVerified() {
|
||||||
|
RegisterRequest reg = new RegisterRequest();
|
||||||
|
reg.setEmail("unverified@example.com");
|
||||||
|
reg.setPassword("password123");
|
||||||
|
reg.setName("Unverified");
|
||||||
|
authService.register(reg);
|
||||||
|
|
||||||
|
LoginRequest login = new LoginRequest();
|
||||||
|
login.setEmail("unverified@example.com");
|
||||||
|
login.setPassword("password123");
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> authService.login(login));
|
||||||
|
assertEquals("Please verify your email address before logging in", ex.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void loginThrowsOnWrongPassword() {
|
void loginThrowsOnWrongPassword() {
|
||||||
RegisterRequest reg = new RegisterRequest();
|
RegisterRequest reg = new RegisterRequest();
|
||||||
@@ -97,6 +170,10 @@ class AuthServiceTest {
|
|||||||
reg.setName("User");
|
reg.setName("User");
|
||||||
authService.register(reg);
|
authService.register(reg);
|
||||||
|
|
||||||
|
User user = userRepository.findByEmail("wrongpw@example.com").get();
|
||||||
|
user.setEmailVerified(true);
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
LoginRequest login = new LoginRequest();
|
LoginRequest login = new LoginRequest();
|
||||||
login.setEmail("wrongpw@example.com");
|
login.setEmail("wrongpw@example.com");
|
||||||
login.setPassword("wrongpw");
|
login.setPassword("wrongpw");
|
||||||
@@ -117,16 +194,305 @@ class AuthServiceTest {
|
|||||||
assertEquals("Invalid email or password", ex.getMessage());
|
assertEquals("Invalid email or password", ex.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyEmailMarksUserVerifiedAndReturnsSetupToken() {
|
||||||
|
User user = User.builder()
|
||||||
|
.email("verify@example.com")
|
||||||
|
.name("Verify")
|
||||||
|
.password("encoded")
|
||||||
|
.emailVerified(false)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
VerificationToken token = VerificationToken.builder()
|
||||||
|
.userId(user.getId())
|
||||||
|
.token("valid-token-123")
|
||||||
|
.expiryDate(LocalDateTime.now().plusHours(24))
|
||||||
|
.used(false)
|
||||||
|
.build();
|
||||||
|
token.onCreate();
|
||||||
|
tokenRepository.save(token);
|
||||||
|
|
||||||
|
VerifyEmailRequest request = new VerifyEmailRequest();
|
||||||
|
request.setToken("valid-token-123");
|
||||||
|
|
||||||
|
VerifyEmailResponse response = authService.verifyEmail(request);
|
||||||
|
|
||||||
|
assertEquals("Email verified successfully", response.getMessage());
|
||||||
|
assertNotNull(response.getSetupToken());
|
||||||
|
|
||||||
|
User updatedUser = userRepository.findById(user.getId()).get();
|
||||||
|
assertTrue(updatedUser.isEmailVerified());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyEmailThrowsForInvalidToken() {
|
||||||
|
VerifyEmailRequest request = new VerifyEmailRequest();
|
||||||
|
request.setToken("nonexistent-token");
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> authService.verifyEmail(request));
|
||||||
|
assertEquals("Invalid verification token", ex.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyEmailThrowsForUsedToken() {
|
||||||
|
User user = User.builder()
|
||||||
|
.email("usedtoken@example.com")
|
||||||
|
.name("Used")
|
||||||
|
.emailVerified(false)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
VerificationToken token = VerificationToken.builder()
|
||||||
|
.userId(user.getId())
|
||||||
|
.token("used-token")
|
||||||
|
.expiryDate(LocalDateTime.now().plusHours(24))
|
||||||
|
.used(true)
|
||||||
|
.build();
|
||||||
|
token.onCreate();
|
||||||
|
tokenRepository.save(token);
|
||||||
|
|
||||||
|
VerifyEmailRequest request = new VerifyEmailRequest();
|
||||||
|
request.setToken("used-token");
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> authService.verifyEmail(request));
|
||||||
|
assertEquals("Verification token has already been used", ex.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void verifyEmailThrowsForExpiredToken() {
|
||||||
|
User user = User.builder()
|
||||||
|
.email("expired@example.com")
|
||||||
|
.name("Expired")
|
||||||
|
.emailVerified(false)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
VerificationToken token = VerificationToken.builder()
|
||||||
|
.userId(user.getId())
|
||||||
|
.token("expired-token")
|
||||||
|
.expiryDate(LocalDateTime.now().minusHours(1))
|
||||||
|
.used(false)
|
||||||
|
.build();
|
||||||
|
token.onCreate();
|
||||||
|
tokenRepository.save(token);
|
||||||
|
|
||||||
|
VerifyEmailRequest request = new VerifyEmailRequest();
|
||||||
|
request.setToken("expired-token");
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> authService.verifyEmail(request));
|
||||||
|
assertEquals("Verification token has expired", ex.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setPasswordUpdatesPassword() {
|
||||||
|
User user = User.builder()
|
||||||
|
.email("setpw@example.com")
|
||||||
|
.name("SetPw")
|
||||||
|
.password("old-encoded")
|
||||||
|
.emailVerified(true)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
VerificationToken token = VerificationToken.builder()
|
||||||
|
.userId(user.getId())
|
||||||
|
.token("verify-token")
|
||||||
|
.setupToken("setup-token-123")
|
||||||
|
.setupTokenUsed(false)
|
||||||
|
.expiryDate(LocalDateTime.now().plusHours(24))
|
||||||
|
.used(true)
|
||||||
|
.build();
|
||||||
|
token.onCreate();
|
||||||
|
tokenRepository.save(token);
|
||||||
|
|
||||||
|
SetPasswordRequest request = new SetPasswordRequest();
|
||||||
|
request.setSetupToken("setup-token-123");
|
||||||
|
request.setPassword("new-password");
|
||||||
|
|
||||||
|
authService.setPassword(request);
|
||||||
|
|
||||||
|
User updatedUser = userRepository.findById(user.getId()).get();
|
||||||
|
assertTrue(updatedUser.getPassword().contains("new-password"));
|
||||||
|
|
||||||
|
VerificationToken updatedToken = tokenRepository.findByToken("verify-token").get();
|
||||||
|
assertTrue(updatedToken.isSetupTokenUsed());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setPasswordThrowsForInvalidSetupToken() {
|
||||||
|
SetPasswordRequest request = new SetPasswordRequest();
|
||||||
|
request.setSetupToken("invalid-setup-token");
|
||||||
|
request.setPassword("new-password");
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> authService.setPassword(request));
|
||||||
|
assertEquals("Invalid setup token", ex.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setPasswordThrowsWhenEmailNotVerifiedFirst() {
|
||||||
|
User user = User.builder()
|
||||||
|
.email("notverified@example.com")
|
||||||
|
.name("NotVerified")
|
||||||
|
.emailVerified(false)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
VerificationToken token = VerificationToken.builder()
|
||||||
|
.userId(user.getId())
|
||||||
|
.token("unused-verify-token")
|
||||||
|
.setupToken("setup-token-bad")
|
||||||
|
.setupTokenUsed(false)
|
||||||
|
.expiryDate(LocalDateTime.now().plusHours(24))
|
||||||
|
.used(false)
|
||||||
|
.build();
|
||||||
|
token.onCreate();
|
||||||
|
tokenRepository.save(token);
|
||||||
|
|
||||||
|
SetPasswordRequest request = new SetPasswordRequest();
|
||||||
|
request.setSetupToken("setup-token-bad");
|
||||||
|
request.setPassword("new-password");
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> authService.setPassword(request));
|
||||||
|
assertEquals("Email must be verified first", ex.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setPasswordThrowsForAlreadyUsedSetupToken() {
|
||||||
|
User user = User.builder()
|
||||||
|
.email("alreadyset@example.com")
|
||||||
|
.name("AlreadySet")
|
||||||
|
.emailVerified(true)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
VerificationToken token = VerificationToken.builder()
|
||||||
|
.userId(user.getId())
|
||||||
|
.token("used-verify-token")
|
||||||
|
.setupToken("already-used-setup")
|
||||||
|
.setupTokenUsed(true)
|
||||||
|
.expiryDate(LocalDateTime.now().plusHours(24))
|
||||||
|
.used(true)
|
||||||
|
.build();
|
||||||
|
token.onCreate();
|
||||||
|
tokenRepository.save(token);
|
||||||
|
|
||||||
|
SetPasswordRequest request = new SetPasswordRequest();
|
||||||
|
request.setSetupToken("already-used-setup");
|
||||||
|
request.setPassword("new-password");
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> authService.setPassword(request));
|
||||||
|
assertEquals("Setup token has already been used", ex.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void setPasswordThrowsForExpiredSetupToken() {
|
||||||
|
User user = User.builder()
|
||||||
|
.email("expiredsetup@example.com")
|
||||||
|
.name("ExpiredSetup")
|
||||||
|
.emailVerified(true)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
VerificationToken token = VerificationToken.builder()
|
||||||
|
.userId(user.getId())
|
||||||
|
.token("expired-verify-token")
|
||||||
|
.setupToken("expired-setup-token")
|
||||||
|
.setupTokenUsed(false)
|
||||||
|
.expiryDate(LocalDateTime.now().minusHours(1))
|
||||||
|
.used(true)
|
||||||
|
.build();
|
||||||
|
token.onCreate();
|
||||||
|
tokenRepository.save(token);
|
||||||
|
|
||||||
|
SetPasswordRequest request = new SetPasswordRequest();
|
||||||
|
request.setSetupToken("expired-setup-token");
|
||||||
|
request.setPassword("new-password");
|
||||||
|
|
||||||
|
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> authService.setPassword(request));
|
||||||
|
assertEquals("Setup token has expired", ex.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resendVerificationSendsNewToken() {
|
||||||
|
User user = User.builder()
|
||||||
|
.email("resend@example.com")
|
||||||
|
.name("Resend")
|
||||||
|
.emailVerified(false)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
ResendVerificationRequest request = new ResendVerificationRequest();
|
||||||
|
request.setEmail("resend@example.com");
|
||||||
|
|
||||||
|
RegistrationResponse response = authService.resendVerification(request);
|
||||||
|
|
||||||
|
assertEquals("If this email is available, a verification link has been sent.", response.getMessage());
|
||||||
|
assertEquals(1, emailService.getSendCount());
|
||||||
|
assertEquals("resend@example.com", emailService.getLastTo());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resendVerificationReturnsGenericForNonExistentEmail() {
|
||||||
|
ResendVerificationRequest request = new ResendVerificationRequest();
|
||||||
|
request.setEmail("nonexistent@example.com");
|
||||||
|
|
||||||
|
RegistrationResponse response = authService.resendVerification(request);
|
||||||
|
|
||||||
|
assertEquals("If this email is available, a verification link has been sent.", response.getMessage());
|
||||||
|
assertEquals(0, emailService.getSendCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void resendVerificationReturnsGenericForAlreadyVerifiedEmail() {
|
||||||
|
User user = User.builder()
|
||||||
|
.email("alreadyverified@example.com")
|
||||||
|
.name("AlreadyVerified")
|
||||||
|
.emailVerified(true)
|
||||||
|
.build();
|
||||||
|
user.onCreate();
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
ResendVerificationRequest request = new ResendVerificationRequest();
|
||||||
|
request.setEmail("alreadyverified@example.com");
|
||||||
|
|
||||||
|
RegistrationResponse response = authService.resendVerification(request);
|
||||||
|
|
||||||
|
assertEquals("If this email is available, a verification link has been sent.", response.getMessage());
|
||||||
|
assertEquals(0, emailService.getSendCount());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void refreshTokenReturnsNewTokens() {
|
void refreshTokenReturnsNewTokens() {
|
||||||
RegisterRequest reg = new RegisterRequest();
|
RegisterRequest reg = new RegisterRequest();
|
||||||
reg.setEmail("refresh@example.com");
|
reg.setEmail("refresh@example.com");
|
||||||
reg.setPassword("password123");
|
reg.setPassword("password123");
|
||||||
reg.setName("Refresh User");
|
reg.setName("Refresh User");
|
||||||
AuthResponse initial = authService.register(reg);
|
authService.register(reg);
|
||||||
|
|
||||||
|
User user = userRepository.findByEmail("refresh@example.com").get();
|
||||||
|
user.setEmailVerified(true);
|
||||||
|
userRepository.save(user);
|
||||||
|
|
||||||
|
FakeJwtConfig jwtConfig = new FakeJwtConfig();
|
||||||
|
String token = jwtConfig.generateRefreshToken(user);
|
||||||
|
|
||||||
RefreshTokenRequest refreshRequest = new RefreshTokenRequest();
|
RefreshTokenRequest refreshRequest = new RefreshTokenRequest();
|
||||||
refreshRequest.setRefreshToken(initial.getRefreshToken());
|
refreshRequest.setRefreshToken(token);
|
||||||
|
|
||||||
AuthResponse response = authService.refreshToken(refreshRequest);
|
AuthResponse response = authService.refreshToken(refreshRequest);
|
||||||
|
|
||||||
@@ -151,6 +517,7 @@ class AuthServiceTest {
|
|||||||
.email("deleted@example.com")
|
.email("deleted@example.com")
|
||||||
.name("Deleted")
|
.name("Deleted")
|
||||||
.build();
|
.build();
|
||||||
|
user.onCreate();
|
||||||
userRepository.save(user);
|
userRepository.save(user);
|
||||||
|
|
||||||
FakeJwtConfig jwtConfig = new FakeJwtConfig();
|
FakeJwtConfig jwtConfig = new FakeJwtConfig();
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package com.krrishg.support;
|
||||||
|
|
||||||
|
import com.krrishg.model.VerificationToken;
|
||||||
|
import com.krrishg.repository.VerificationTokenRepository;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
public class FakeVerificationTokenRepository extends InMemoryRepository<VerificationToken, UUID> implements VerificationTokenRepository {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected UUID getId(VerificationToken entity) {
|
||||||
|
return entity.getId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected VerificationToken setId(VerificationToken entity, UUID id) {
|
||||||
|
entity.setId(id);
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected UUID generateId() {
|
||||||
|
return UUID.randomUUID();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<VerificationToken> findByToken(String token) {
|
||||||
|
return store.values().stream()
|
||||||
|
.filter(t -> t.getToken().equals(token))
|
||||||
|
.findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<VerificationToken> findBySetupToken(String setupToken) {
|
||||||
|
return store.values().stream()
|
||||||
|
.filter(t -> setupToken.equals(t.getSetupToken()))
|
||||||
|
.findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void deleteByUserId(UUID userId) {
|
||||||
|
store.values().removeIf(t -> t.getUserId().equals(userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<VerificationToken> findByUsedFalseAndExpiryDateBefore(LocalDateTime now) {
|
||||||
|
return store.values().stream()
|
||||||
|
.filter(t -> !t.isUsed())
|
||||||
|
.filter(t -> t.getExpiryDate().isBefore(now))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.krrishg.support;
|
||||||
|
|
||||||
|
import com.krrishg.service.EmailService;
|
||||||
|
|
||||||
|
public class StubEmailService extends EmailService {
|
||||||
|
|
||||||
|
private String lastTo;
|
||||||
|
private String lastToken;
|
||||||
|
private int sendCount;
|
||||||
|
|
||||||
|
public StubEmailService() {
|
||||||
|
super(null, "http://localhost:4200");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sendVerificationEmail(String to, String name, String token) {
|
||||||
|
this.lastTo = to;
|
||||||
|
this.lastToken = token;
|
||||||
|
this.sendCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLastTo() {
|
||||||
|
return lastTo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLastToken() {
|
||||||
|
return lastToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getSendCount() {
|
||||||
|
return sendCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reset() {
|
||||||
|
lastTo = null;
|
||||||
|
lastToken = null;
|
||||||
|
sendCount = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,10 @@ export const routes: Routes = [
|
|||||||
loadComponent: () => import('./auth/login/login.component').then(m => m.LoginComponent),
|
loadComponent: () => import('./auth/login/login.component').then(m => m.LoginComponent),
|
||||||
canActivate: [LoginGuard],
|
canActivate: [LoginGuard],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'verify-email',
|
||||||
|
loadComponent: () => import('./auth/verify-email/verify-email.component').then(m => m.VerifyEmailComponent),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'register',
|
path: 'register',
|
||||||
loadComponent: () => import('./auth/register/register.component').then(m => m.RegisterComponent),
|
loadComponent: () => import('./auth/register/register.component').then(m => m.RegisterComponent),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Component } from '@angular/core';
|
import { Component, OnInit } from '@angular/core';
|
||||||
import { Router, RouterLink } from '@angular/router';
|
import { Router, ActivatedRoute, RouterLink } from '@angular/router';
|
||||||
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
|
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
import { MatCardModule } from '@angular/material/card';
|
import { MatCardModule } from '@angular/material/card';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
@@ -25,6 +25,10 @@ import { NgIf } from '@angular/common';
|
|||||||
<p class="text-gray-500 mt-1">Sign in to your account</p>
|
<p class="text-gray-500 mt-1">Sign in to your account</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div *ngIf="showVerifiedMessage" class="bg-green-50 border border-green-200 text-green-700 text-sm rounded-lg p-3 mb-4">
|
||||||
|
Your account is ready. Please sign in.
|
||||||
|
</div>
|
||||||
|
|
||||||
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()" class="flex flex-col gap-4">
|
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()" class="flex flex-col gap-4">
|
||||||
<mat-form-field appearance="outline" class="w-full">
|
<mat-form-field appearance="outline" class="w-full">
|
||||||
<mat-label>Email</mat-label>
|
<mat-label>Email</mat-label>
|
||||||
@@ -41,6 +45,13 @@ import { NgIf } from '@angular/common';
|
|||||||
|
|
||||||
<div *ngIf="error" class="text-red-600 text-sm">{{ error }}</div>
|
<div *ngIf="error" class="text-red-600 text-sm">{{ error }}</div>
|
||||||
|
|
||||||
|
<div *ngIf="showResendLink" class="text-sm text-center">
|
||||||
|
<a (click)="resendVerification()" class="text-indigo-600 font-medium hover:underline cursor-pointer">
|
||||||
|
Resend verification email
|
||||||
|
</a>
|
||||||
|
<div *ngIf="resendMessage" class="text-green-600 mt-1">{{ resendMessage }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button mat-flat-button color="primary" type="submit" [disabled]="loading" class="w-full py-2">
|
<button mat-flat-button color="primary" type="submit" [disabled]="loading" class="w-full py-2">
|
||||||
<mat-spinner *ngIf="loading" diameter="20" class="inline-block mr-2"></mat-spinner>
|
<mat-spinner *ngIf="loading" diameter="20" class="inline-block mr-2"></mat-spinner>
|
||||||
{{ loading ? 'Signing in...' : 'Sign In' }}
|
{{ loading ? 'Signing in...' : 'Sign In' }}
|
||||||
@@ -55,31 +66,63 @@ import { NgIf } from '@angular/common';
|
|||||||
</div>
|
</div>
|
||||||
`,
|
`,
|
||||||
})
|
})
|
||||||
export class LoginComponent {
|
export class LoginComponent implements OnInit {
|
||||||
loginForm = this.fb.group({
|
loginForm = this.fb.group({
|
||||||
email: ['', [Validators.required, Validators.email]],
|
email: ['', [Validators.required, Validators.email]],
|
||||||
password: ['', Validators.required],
|
password: ['', Validators.required],
|
||||||
});
|
});
|
||||||
loading = false;
|
loading = false;
|
||||||
error = '';
|
error = '';
|
||||||
|
showResendLink = false;
|
||||||
|
resendMessage = '';
|
||||||
|
showVerifiedMessage = false;
|
||||||
|
private unverifiedEmail = '';
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private fb: FormBuilder,
|
private fb: FormBuilder,
|
||||||
private authService: AuthService,
|
private authService: AuthService,
|
||||||
private router: Router,
|
private router: Router,
|
||||||
|
private route: ActivatedRoute,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
if (this.route.snapshot.queryParams['verified'] === 'true') {
|
||||||
|
this.showVerifiedMessage = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onSubmit(): void {
|
onSubmit(): void {
|
||||||
if (this.loginForm.invalid) return;
|
if (this.loginForm.invalid) return;
|
||||||
this.loading = true;
|
this.loading = true;
|
||||||
this.error = '';
|
this.error = '';
|
||||||
|
this.showResendLink = false;
|
||||||
|
this.resendMessage = '';
|
||||||
const { email, password } = this.loginForm.value;
|
const { email, password } = this.loginForm.value;
|
||||||
this.authService.login(email!, password!).subscribe({
|
this.authService.login(email!, password!).subscribe({
|
||||||
next: () => this.router.navigate(['/dashboard']),
|
next: () => this.router.navigate(['/dashboard']),
|
||||||
error: (err) => {
|
error: (err) => {
|
||||||
this.error = err.error?.message || err.error?.error || 'Invalid email or password';
|
const msg = err.error?.detail || err.error?.message || 'Invalid email or password';
|
||||||
|
if (msg.toLowerCase().includes('verify your email')) {
|
||||||
|
this.error = 'Please verify your email address before logging in.';
|
||||||
|
this.showResendLink = true;
|
||||||
|
this.unverifiedEmail = email!;
|
||||||
|
} else {
|
||||||
|
this.error = msg;
|
||||||
|
}
|
||||||
this.loading = false;
|
this.loading = false;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
resendVerification(): void {
|
||||||
|
if (!this.unverifiedEmail) return;
|
||||||
|
this.authService.resendVerification(this.unverifiedEmail).subscribe({
|
||||||
|
next: () => {
|
||||||
|
this.resendMessage = 'Verification email resent.';
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.resendMessage = 'Failed to resend. Please try again later.';
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ export class RegisterComponent {
|
|||||||
this.error = '';
|
this.error = '';
|
||||||
const { name, email, password } = this.registerForm.value;
|
const { name, email, password } = this.registerForm.value;
|
||||||
this.authService.register(name!, email!, password!).subscribe({
|
this.authService.register(name!, email!, password!).subscribe({
|
||||||
next: () => this.router.navigate(['/dashboard']),
|
next: () => this.router.navigate(['/verify-email'], { queryParams: { email: email! } }),
|
||||||
error: (err) => {
|
error: (err) => {
|
||||||
this.error = err.error?.message || err.error?.error || 'Registration failed';
|
this.error = err.error?.message || err.error?.error || 'Registration failed';
|
||||||
this.loading = false;
|
this.loading = false;
|
||||||
|
|||||||
226
frontend/src/app/auth/verify-email/verify-email.component.ts
Normal file
226
frontend/src/app/auth/verify-email/verify-email.component.ts
Normal file
@@ -0,0 +1,226 @@
|
|||||||
|
import { Component, OnInit } from '@angular/core';
|
||||||
|
import { Router, ActivatedRoute, RouterLink } from '@angular/router';
|
||||||
|
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
|
import { NgIf } from '@angular/common';
|
||||||
|
import { MatCardModule } from '@angular/material/card';
|
||||||
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
|
import { MatInputModule } from '@angular/material/input';
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||||
|
import { AuthService } from '../../core/services/auth.service';
|
||||||
|
|
||||||
|
type PageState = 'check-email' | 'verifying' | 'verified' | 'set-password' | 'error';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-verify-email',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
RouterLink, ReactiveFormsModule, NgIf,
|
||||||
|
MatCardModule, MatFormFieldModule, MatInputModule, MatButtonModule,
|
||||||
|
MatProgressSpinnerModule,
|
||||||
|
],
|
||||||
|
template: `
|
||||||
|
<div class="min-h-screen flex items-center justify-center bg-gray-50 px-4">
|
||||||
|
<mat-card class="w-full max-w-md p-8">
|
||||||
|
<div class="text-center mb-8">
|
||||||
|
<h1 class="text-3xl font-bold text-indigo-600">Indie</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div *ngIf="state === 'check-email'" class="text-center">
|
||||||
|
<div class="text-5xl mb-4">📧</div>
|
||||||
|
<h2 class="text-xl font-semibold text-gray-800 mb-2">Check your email</h2>
|
||||||
|
<p class="text-gray-500 mb-6">
|
||||||
|
We sent a verification link to <strong>{{ email }}</strong>
|
||||||
|
</p>
|
||||||
|
<p class="text-sm text-gray-400 mb-6">The link expires in 24 hours.</p>
|
||||||
|
|
||||||
|
<div *ngIf="resendMessage" class="text-green-600 text-sm mb-4">{{ resendMessage }}</div>
|
||||||
|
<div *ngIf="resendError" class="text-red-600 text-sm mb-4">{{ resendError }}</div>
|
||||||
|
|
||||||
|
<button mat-stroked-button (click)="resend()" [disabled]="resending" class="w-full mb-3">
|
||||||
|
<mat-spinner *ngIf="resending" diameter="16" class="inline-block mr-2"></mat-spinner>
|
||||||
|
{{ resending ? 'Sending...' : 'Resend verification email' }}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<a routerLink="/login" class="block text-sm text-indigo-600 font-medium hover:underline">Back to login</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div *ngIf="state === 'verifying'" class="text-center">
|
||||||
|
<mat-spinner diameter="40" class="mx-auto mb-4"></mat-spinner>
|
||||||
|
<p class="text-gray-500">Verifying your email...</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div *ngIf="state === 'verified'" class="text-center">
|
||||||
|
<div class="text-5xl mb-4">✅</div>
|
||||||
|
<h2 class="text-xl font-semibold text-gray-800 mb-2">Email verified!</h2>
|
||||||
|
<p class="text-gray-500 mb-6">Your email has been verified. Now set your password to activate your account.</p>
|
||||||
|
<button mat-flat-button color="primary" (click)="state = 'set-password'" class="w-full">
|
||||||
|
Set Your Password
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div *ngIf="state === 'set-password'">
|
||||||
|
<h2 class="text-xl font-semibold text-gray-800 mb-4 text-center">Set your password</h2>
|
||||||
|
<form [formGroup]="passwordForm" (ngSubmit)="onSetPassword()" class="flex flex-col gap-4">
|
||||||
|
<mat-form-field appearance="outline" class="w-full">
|
||||||
|
<mat-label>New Password</mat-label>
|
||||||
|
<input matInput type="password" formControlName="password" />
|
||||||
|
<mat-error *ngIf="passwordForm.get('password')?.hasError('required')">Password is required</mat-error>
|
||||||
|
<mat-error *ngIf="passwordForm.get('password')?.hasError('minlength')">At least 8 characters</mat-error>
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
<mat-form-field appearance="outline" class="w-full">
|
||||||
|
<mat-label>Confirm Password</mat-label>
|
||||||
|
<input matInput type="password" formControlName="confirmPassword" />
|
||||||
|
<mat-error *ngIf="passwordForm.get('confirmPassword')?.hasError('required')">Please confirm your password</mat-error>
|
||||||
|
<mat-error *ngIf="passwordForm.hasError('mismatch')">Passwords do not match</mat-error>
|
||||||
|
</mat-form-field>
|
||||||
|
|
||||||
|
<div *ngIf="passwordError" class="text-red-600 text-sm">{{ passwordError }}</div>
|
||||||
|
|
||||||
|
<button mat-flat-button color="primary" type="submit" [disabled]="passwordLoading || passwordForm.invalid" class="w-full py-2">
|
||||||
|
<mat-spinner *ngIf="passwordLoading" diameter="20" class="inline-block mr-2"></mat-spinner>
|
||||||
|
{{ passwordLoading ? 'Setting password...' : 'Activate Account' }}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div *ngIf="state === 'error'" class="text-center">
|
||||||
|
<div class="text-5xl mb-4">❌</div>
|
||||||
|
<h2 class="text-xl font-semibold text-gray-800 mb-2">{{ errorTitle }}</h2>
|
||||||
|
<p class="text-gray-500 mb-6">{{ errorMessage }}</p>
|
||||||
|
|
||||||
|
<button *ngIf="showResend" mat-stroked-button (click)="resend()" [disabled]="resending" class="w-full mb-3">
|
||||||
|
{{ resending ? 'Sending...' : 'Resend verification email' }}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<a *ngIf="!showResend" routerLink="/register" class="block text-sm text-indigo-600 font-medium hover:underline mb-2">Create a new account</a>
|
||||||
|
<a routerLink="/login" class="block text-sm text-indigo-600 font-medium hover:underline">Back to login</a>
|
||||||
|
</div>
|
||||||
|
</mat-card>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
})
|
||||||
|
export class VerifyEmailComponent implements OnInit {
|
||||||
|
state: PageState = 'check-email';
|
||||||
|
email = '';
|
||||||
|
errorTitle = '';
|
||||||
|
errorMessage = '';
|
||||||
|
showResend = false;
|
||||||
|
resendMessage = '';
|
||||||
|
resendError = '';
|
||||||
|
resending = false;
|
||||||
|
|
||||||
|
private setupToken = '';
|
||||||
|
passwordLoading = false;
|
||||||
|
passwordError = '';
|
||||||
|
|
||||||
|
passwordForm = this.fb.group({
|
||||||
|
password: ['', [Validators.required, Validators.minLength(8)]],
|
||||||
|
confirmPassword: ['', Validators.required],
|
||||||
|
}, { validators: this.passwordsMatch });
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private route: ActivatedRoute,
|
||||||
|
private router: Router,
|
||||||
|
private authService: AuthService,
|
||||||
|
private fb: FormBuilder,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.route.queryParams.subscribe(params => {
|
||||||
|
const token = params['token'];
|
||||||
|
const email = params['email'];
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
this.verify(token);
|
||||||
|
} else if (email) {
|
||||||
|
this.email = email;
|
||||||
|
this.state = 'check-email';
|
||||||
|
} else {
|
||||||
|
this.state = 'check-email';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private verify(token: string): void {
|
||||||
|
this.state = 'verifying';
|
||||||
|
this.authService.verifyEmail(token).subscribe({
|
||||||
|
next: (res) => {
|
||||||
|
if (res.setupToken) {
|
||||||
|
this.setupToken = res.setupToken;
|
||||||
|
this.state = 'verified';
|
||||||
|
} else {
|
||||||
|
this.state = 'verified';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
const msg = err.error?.detail || err.error?.message || 'Verification failed';
|
||||||
|
if (msg.toLowerCase().includes('expired')) {
|
||||||
|
this.errorTitle = 'Link expired';
|
||||||
|
this.errorMessage = 'This verification link has expired. Request a new one.';
|
||||||
|
this.showResend = true;
|
||||||
|
} else if (msg.toLowerCase().includes('already been used')) {
|
||||||
|
this.errorTitle = 'Already verified';
|
||||||
|
this.errorMessage = 'This link has already been used. Your email may already be verified. Try logging in.';
|
||||||
|
this.showResend = false;
|
||||||
|
} else {
|
||||||
|
this.errorTitle = 'Verification failed';
|
||||||
|
this.errorMessage = msg;
|
||||||
|
this.showResend = true;
|
||||||
|
}
|
||||||
|
this.state = 'error';
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
resend(): void {
|
||||||
|
if (!this.email) {
|
||||||
|
const token = this.route.snapshot.queryParams['token'];
|
||||||
|
this.authService.verifyEmail(token).subscribe({
|
||||||
|
next: () => {},
|
||||||
|
error: (err) => {
|
||||||
|
this.email = err.error?.email || '';
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.resending = true;
|
||||||
|
this.resendMessage = '';
|
||||||
|
this.resendError = '';
|
||||||
|
this.authService.resendVerification(this.email).subscribe({
|
||||||
|
next: () => {
|
||||||
|
this.resendMessage = 'Verification email resent. Please check your inbox.';
|
||||||
|
this.resending = false;
|
||||||
|
this.state = 'check-email';
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
this.resendError = 'Failed to resend. Please try again later.';
|
||||||
|
this.resending = false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onSetPassword(): void {
|
||||||
|
if (this.passwordForm.invalid) return;
|
||||||
|
this.passwordLoading = true;
|
||||||
|
this.passwordError = '';
|
||||||
|
|
||||||
|
this.authService.setPassword(this.setupToken, this.passwordForm.value.password!).subscribe({
|
||||||
|
next: () => {
|
||||||
|
this.router.navigate(['/login'], { queryParams: { verified: 'true' } });
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
this.passwordError = err.error?.detail || err.error?.message || 'Failed to set password';
|
||||||
|
this.passwordLoading = false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private passwordsMatch(group: any): { mismatch: boolean } | null {
|
||||||
|
const password = group.get('password')?.value;
|
||||||
|
const confirm = group.get('confirmPassword')?.value;
|
||||||
|
return password === confirm ? null : { mismatch: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,9 +14,8 @@ export class AuthService {
|
|||||||
|
|
||||||
constructor(private http: HttpClient) {}
|
constructor(private http: HttpClient) {}
|
||||||
|
|
||||||
register(name: string, email: string, password: string): Observable<AuthResponse> {
|
register(name: string, email: string, password: string): Observable<{ message: string }> {
|
||||||
return this.http.post<AuthResponse>('/api/auth/register', { name, email, password })
|
return this.http.post<{ message: string }>('/api/auth/register', { name, email, password });
|
||||||
.pipe(tap(res => this.setSession(res)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
login(email: string, password: string): Observable<AuthResponse> {
|
login(email: string, password: string): Observable<AuthResponse> {
|
||||||
@@ -34,6 +33,18 @@ export class AuthService {
|
|||||||
.pipe(tap(() => this.clearSession()));
|
.pipe(tap(() => this.clearSession()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
verifyEmail(token: string): Observable<{ message: string; setupToken?: string }> {
|
||||||
|
return this.http.post<{ message: string; setupToken?: string }>('/api/auth/verify-email', { token });
|
||||||
|
}
|
||||||
|
|
||||||
|
resendVerification(email: string): Observable<{ message: string }> {
|
||||||
|
return this.http.post<{ message: string }>('/api/auth/resend-verification', { email });
|
||||||
|
}
|
||||||
|
|
||||||
|
setPassword(setupToken: string, password: string): Observable<void> {
|
||||||
|
return this.http.post<void>('/api/auth/set-password', { setupToken, password });
|
||||||
|
}
|
||||||
|
|
||||||
getAccessToken(): string | null {
|
getAccessToken(): string | null {
|
||||||
return localStorage.getItem(this.ACCESS_TOKEN_KEY);
|
return localStorage.getItem(this.ACCESS_TOKEN_KEY);
|
||||||
}
|
}
|
||||||
@@ -72,5 +83,4 @@ export class AuthService {
|
|||||||
const data = localStorage.getItem(this.USER_KEY);
|
const data = localStorage.getItem(this.USER_KEY);
|
||||||
return data ? JSON.parse(data) : null;
|
return data ? JSON.parse(data) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user