package com.qiaoba.api.auth.utils;

import com.qiaoba.api.auth.entity.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * SecurityUtil
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022/8/16 0016 下午 14:51
 */
public class SecurityUtil {

    private static final BCryptPasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();

    /**
     * 获取登录用户的账号
     *
     * @return username
     */
    public static String getLoginUsername() {
        return getLoginUser().getUsername();
    }

    /**
     * 获取登录用户的账号
     *
     * @return nickname
     */
    public static String getLoginNickname() {
        return getLoginUser().getNickname();
    }

    /**
     * 获取登录用户的ID
     *
     * @return userId
     */
    public static String getLoginUserId() {
        return getLoginUser().getUserId();
    }


    public static LoginUser getLoginUser() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        return (LoginUser) auth.getPrincipal();
    }

    /**
     * 加密密码
     *
     * @param password 原密码
     * @return 加密后密码
     */
    public static String encryptPassword(String password) {
        return PASSWORD_ENCODER.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        return PASSWORD_ENCODER.matches(rawPassword, encodedPassword);
    }
}
