Newer
Older
teacher-diary / src / main / java / ru / mcs / diary / auth / CustomUserDetails.java
package ru.mcs.diary.auth;

import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import ru.mcs.diary.parent.Parent;
import ru.mcs.diary.teacher.Teacher;

import java.util.Collection;
import java.util.Collections;

@Getter
public class CustomUserDetails implements UserDetails {

    private final Long id;
    private final String email;
    private final String password;
    private final String fullName;
    private final Role role;
    private final boolean enabled;
    private final Long teacherId; // Для родителя - ID преподавателя

    // Конструктор для Teacher
    public CustomUserDetails(Teacher teacher) {
        this.id = teacher.getId();
        this.email = teacher.getEmail();
        this.password = teacher.getPassword();
        this.fullName = teacher.getFullName();
        this.role = Role.TEACHER;
        this.enabled = teacher.getEnabled();
        this.teacherId = teacher.getId();
    }

    // Конструктор для Parent
    public CustomUserDetails(Parent parent) {
        this.id = parent.getId();
        this.email = parent.getEmail();
        this.password = parent.getPassword();
        this.fullName = parent.getFullName();
        this.role = Role.PARENT;
        this.enabled = parent.getEnabled();
        this.teacherId = parent.getTeacher().getId();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.singletonList(
                new SimpleGrantedAuthority("ROLE_" + role.name())
        );
    }

    @Override
    public String getUsername() {
        return email;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    public boolean isTeacher() {
        return role == Role.TEACHER;
    }

    public boolean isParent() {
        return role == Role.PARENT;
    }
}