package me.chyxion.tigon.shiro.service.support;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import me.chyxion.tigon.shiro.model.AuthUser;
import me.chyxion.tigon.shiro.service.AuthService;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthenticatedException;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * May 12, 2016 2:34:35 PM
 */
public class AuthServiceSupport implements AuthService {

    /**
     * {@inheritDoc}
     */
    @Override
    public void logout() {
        SecurityUtils.getSubject().logout();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <U> AuthUser<U> getAuthUser() {
        Session session = getSession();
        if (session == null) {
            throw new UnauthenticatedException();
        }
        AuthUser<U> user = AuthUser.get(session);
        if (user == null) {
            throw new UnauthenticatedException();
        }
        return user;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isAuthenticated() {
        Session session = getSession();
        AuthUser<?> user = null;
        if (session != null) {
            user = AuthUser.get(session);
        }
        return user != null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Session getSession() {
        return SecurityUtils.getSubject().getSession(false);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <U> AuthUser<U> login(String loginId, String password) {
        return login(loginId, password, false);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <U> AuthUser<U> login(String loginId, String password,
            boolean rememberMe) {
        SecurityUtils.getSubject().login(new UsernamePasswordToken(loginId, password, rememberMe));
        return getAuthUser();
    }
}
