mirror of https://github.com/Rekoe/rk_svnadmin
可以启动
parent
988569068d
commit
2d13705948
|
@ -1,4 +1,5 @@
|
|||
eclipse.preferences.version=1
|
||||
encoding//src/main/java=UTF-8
|
||||
encoding//src/main/resources=UTF-8
|
||||
encoding//src/main/resources/msg/zh_CN/MessageResources.properties=UTF-8
|
||||
encoding/<project>=UTF-8
|
||||
|
|
9
pom.xml
9
pom.xml
|
@ -61,9 +61,8 @@
|
|||
<version>20090211</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-email</artifactId>
|
||||
<version>1.4</version>
|
||||
<groupId>org.nutz</groupId>
|
||||
<artifactId>nutzboot-starter-email</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.nutz</groupId>
|
||||
|
@ -114,6 +113,10 @@
|
|||
<groupId>org.nutz</groupId>
|
||||
<artifactId>nutzboot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.nutz</groupId>
|
||||
<artifactId>nutzboot-starter-ngrok</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.nutz</groupId>
|
||||
<artifactId>nutzboot-starter-jetty</artifactId>
|
||||
|
|
|
@ -0,0 +1,197 @@
|
|||
package com.rekoe;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.shiro.authz.permission.PermissionResolver;
|
||||
import org.apache.shiro.crypto.RandomNumberGenerator;
|
||||
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
|
||||
import org.apache.shiro.crypto.hash.Sha256Hash;
|
||||
import org.nutz.boot.NbApp;
|
||||
import org.nutz.boot.starter.freemarker.FreeMarkerConfigurer;
|
||||
import org.nutz.dao.Dao;
|
||||
import org.nutz.dao.entity.annotation.Table;
|
||||
import org.nutz.dao.impl.FileSqlManager;
|
||||
import org.nutz.dao.sql.Sql;
|
||||
import org.nutz.dao.util.Daos;
|
||||
import org.nutz.ioc.loader.annotation.Inject;
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.lang.ContinueLoop;
|
||||
import org.nutz.lang.Each;
|
||||
import org.nutz.lang.ExitLoop;
|
||||
import org.nutz.lang.Lang;
|
||||
import org.nutz.lang.LoopException;
|
||||
import org.nutz.mvc.annotation.Encoding;
|
||||
import org.nutz.mvc.annotation.Fail;
|
||||
import org.nutz.mvc.annotation.IocBy;
|
||||
import org.nutz.mvc.annotation.Localization;
|
||||
import org.nutz.plugins.cache.dao.DaoCacheInterceptor;
|
||||
import org.nutz.resource.Scans;
|
||||
|
||||
import com.rekoe.domain.Pj;
|
||||
import com.rekoe.domain.PjGrUsr;
|
||||
import com.rekoe.domain.ProjectConfig;
|
||||
import com.rekoe.domain.User;
|
||||
import com.rekoe.domain.Usr;
|
||||
import com.rekoe.service.AuthorityService;
|
||||
import com.rekoe.service.ProjectConfigService;
|
||||
import com.rekoe.shiro.freemarker.AuthenticatedTag;
|
||||
import com.rekoe.shiro.freemarker.GuestTag;
|
||||
import com.rekoe.shiro.freemarker.HasAnyPermissionTag;
|
||||
import com.rekoe.shiro.freemarker.HasAnyRolesTag;
|
||||
import com.rekoe.shiro.freemarker.HasPermissionTag;
|
||||
import com.rekoe.shiro.freemarker.HasRoleTag;
|
||||
import com.rekoe.shiro.freemarker.LacksPermissionTag;
|
||||
import com.rekoe.shiro.freemarker.LacksRoleTag;
|
||||
import com.rekoe.shiro.freemarker.NotAuthenticatedTag;
|
||||
import com.rekoe.shiro.freemarker.PrincipalTag;
|
||||
import com.rekoe.shiro.freemarker.UserTag;
|
||||
import com.rekoe.web.freemarker.CurrentTimeDirective;
|
||||
import com.rekoe.web.freemarker.HtmlCutDirective;
|
||||
import com.rekoe.web.freemarker.PaginationDirective;
|
||||
import com.rekoe.web.freemarker.PermissionDirective;
|
||||
import com.rekoe.web.freemarker.PermissionShiroFreemarker;
|
||||
import com.rekoe.web.freemarker.ProcessTimeDirective;
|
||||
import com.rekoe.web.freemarker.TimeFormatDirective;
|
||||
|
||||
import freemarker.template.SimpleHash;
|
||||
|
||||
@Fail(">>:/admin/common/unauthorized.rk")
|
||||
@Encoding(input = "UTF-8", output = "UTF-8")
|
||||
@Localization(value = "msg/", defaultLocalizationKey = "zh-CN")
|
||||
@IocBean(create = "init")
|
||||
@IocBy(args = { "*slog" })
|
||||
public class CloudLauncher {
|
||||
|
||||
@Inject
|
||||
private Dao dao;
|
||||
|
||||
@Inject
|
||||
private AuthorityService authorityService;
|
||||
|
||||
@Inject
|
||||
private FreeMarkerConfigurer freeMarkerConfigurer;
|
||||
|
||||
@Inject
|
||||
private ProjectConfigService projectConfigService;
|
||||
|
||||
@Inject
|
||||
private SimpleHash shiroTags;
|
||||
|
||||
@Inject
|
||||
private PermissionShiroFreemarker permissionShiro;
|
||||
|
||||
@Inject
|
||||
private ProcessTimeDirective process;
|
||||
|
||||
@Inject
|
||||
private HtmlCutDirective htmlCut;
|
||||
|
||||
@Inject
|
||||
private TimeFormatDirective timeFormat;
|
||||
|
||||
@Inject
|
||||
private CurrentTimeDirective currentTime;
|
||||
|
||||
@Inject
|
||||
private PaginationDirective pagination;
|
||||
|
||||
@Inject
|
||||
private PermissionDirective permission;
|
||||
|
||||
@IocBean(name = "shiroTags")
|
||||
@SuppressWarnings("deprecation")
|
||||
public SimpleHash createShiroTags() {
|
||||
return new SimpleHash(new HashMap<String, Object>()) {
|
||||
private static final long serialVersionUID = -2531751737433483659L;
|
||||
{
|
||||
put("authenticated", new AuthenticatedTag());
|
||||
put("guest", new GuestTag());
|
||||
put("hasAnyRoles", new HasAnyRolesTag());
|
||||
put("hasPermission", new HasPermissionTag());
|
||||
put("hasAnyPermission", new HasAnyPermissionTag());
|
||||
put("hasRole", new HasRoleTag());
|
||||
put("lacksPermission", new LacksPermissionTag());
|
||||
put("lacksRole", new LacksRoleTag());
|
||||
put("notAuthenticated", new NotAuthenticatedTag());
|
||||
put("principal", new PrincipalTag());
|
||||
put("user", new UserTag());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@IocBean(name = "permissionShiro")
|
||||
public PermissionShiroFreemarker createPermissionResolver(@Inject PermissionResolver permissionResolver) {
|
||||
return new com.rekoe.web.freemarker.PermissionShiroFreemarker(permissionResolver);
|
||||
}
|
||||
|
||||
@IocBean(name = "permissionResolver")
|
||||
public PermissionResolver createPermissionResolver() {
|
||||
return new org.apache.shiro.authz.permission.WildcardPermissionResolver();
|
||||
}
|
||||
|
||||
@Inject
|
||||
private DaoCacheInterceptor daoCacheInterceptor;
|
||||
|
||||
public void init() {
|
||||
freeMarkerConfigurer.getConfiguration().setAutoImports(new HashMap<String, String>(2) {
|
||||
private static final long serialVersionUID = 7208484815721559298L;
|
||||
{
|
||||
put("p", "/ftl/pony/index.ftl");
|
||||
put("s", "/ftl/spring.ftl");
|
||||
}
|
||||
});
|
||||
|
||||
freeMarkerConfigurer.addTags(new HashMap<String, Object>() {
|
||||
private static final long serialVersionUID = 2819227381581642466L;
|
||||
{
|
||||
put("shiro", shiroTags);
|
||||
put("perm_chow", permissionShiro);
|
||||
put("cms_perm", permission);
|
||||
put("process_time", process);
|
||||
put("pagination", pagination);
|
||||
put("htmlCut", htmlCut);
|
||||
put("timeFormat", timeFormat);
|
||||
put("currentTime", currentTime);
|
||||
}
|
||||
});
|
||||
dao.create(PjGrUsr.class, false);
|
||||
Daos.createTablesInPackage(dao, User.class.getPackage().getName(), false);
|
||||
Daos.migration(dao, Usr.class, true, true, false);
|
||||
Daos.migration(dao, Pj.class, true, true, false);
|
||||
Daos.migration(dao, ProjectConfig.class, true, true, false);
|
||||
if (0 == dao.count(User.class)) {
|
||||
FileSqlManager fm = new FileSqlManager("init_system_h2.sql");
|
||||
List<Sql> sqlList = fm.createCombo(fm.keys());
|
||||
dao.execute(sqlList.toArray(new Sql[sqlList.size()]));
|
||||
List<User> userList = dao.query(User.class, null);
|
||||
for (User user : userList) {
|
||||
RandomNumberGenerator rng = new SecureRandomNumberGenerator();
|
||||
String salt = rng.nextBytes().toBase64();
|
||||
String hashedPasswordBase64 = new Sha256Hash("123", salt, 1024).toBase64();
|
||||
user.setSalt(salt);
|
||||
user.setPassword(hashedPasswordBase64);
|
||||
dao.update(user);
|
||||
}
|
||||
}
|
||||
authorityService.initFormPackage("com.rekoe");
|
||||
projectConfigService.init();
|
||||
|
||||
List<Class<?>> clazzList = Scans.me().scanPackage("com.rekoe.domain");
|
||||
Lang.each(clazzList, new Each<Class<?>>() {
|
||||
@Override
|
||||
public void invoke(int index, Class<?> clazz, int length) throws ExitLoop, ContinueLoop, LoopException {
|
||||
Table table = clazz.getAnnotation(Table.class);
|
||||
if (Lang.isNotEmpty(table)) {
|
||||
String name = table.value();
|
||||
daoCacheInterceptor.addCachedTableName(StringUtils.trim(name));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
new NbApp().setPrintProcDoc(true).run();
|
||||
}
|
||||
}
|
|
@ -1,80 +0,0 @@
|
|||
package com.rekoe;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.shiro.crypto.RandomNumberGenerator;
|
||||
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
|
||||
import org.apache.shiro.crypto.hash.Sha256Hash;
|
||||
import org.nutz.dao.Dao;
|
||||
import org.nutz.dao.impl.FileSqlManager;
|
||||
import org.nutz.dao.sql.Sql;
|
||||
import org.nutz.dao.util.Daos;
|
||||
import org.nutz.ioc.loader.annotation.Inject;
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.mvc.annotation.Encoding;
|
||||
import org.nutz.mvc.annotation.Fail;
|
||||
import org.nutz.mvc.annotation.IocBy;
|
||||
import org.nutz.mvc.annotation.Localization;
|
||||
|
||||
import com.rekoe.domain.Pj;
|
||||
import com.rekoe.domain.PjGrUsr;
|
||||
import com.rekoe.domain.ProjectConfig;
|
||||
import com.rekoe.domain.User;
|
||||
import com.rekoe.domain.Usr;
|
||||
import com.rekoe.service.AuthorityService;
|
||||
import com.rekoe.service.ProjectConfigService;
|
||||
|
||||
import freemarker.template.Configuration;
|
||||
|
||||
@Fail(">>:/admin/common/unauthorized.rk")
|
||||
@Encoding(input = "UTF-8", output = "UTF-8")
|
||||
@Localization(value = "msg/", defaultLocalizationKey = "zh-CN")
|
||||
@IocBean(create = "init")
|
||||
@IocBy(args = { "*slog" })
|
||||
public class MainModule {
|
||||
|
||||
@Inject
|
||||
private Dao dao;
|
||||
|
||||
@Inject
|
||||
private AuthorityService authorityService;
|
||||
|
||||
@Inject
|
||||
private ProjectConfigService projectConfigService;
|
||||
|
||||
@Inject
|
||||
private Configuration configuration;
|
||||
|
||||
public void init() {
|
||||
configuration.setAutoImports(new HashMap<String, String>(2) {
|
||||
private static final long serialVersionUID = 7208484815721559298L;
|
||||
{
|
||||
put("p", "/ftl/pony/index.ftl");
|
||||
put("s", "/ftl/spring.ftl");
|
||||
}
|
||||
});
|
||||
|
||||
dao.create(PjGrUsr.class, false);
|
||||
Daos.createTablesInPackage(dao, User.class.getPackage().getName(), false);
|
||||
Daos.migration(dao, Usr.class, true, true, false);
|
||||
Daos.migration(dao, Pj.class, true, true, false);
|
||||
Daos.migration(dao, ProjectConfig.class, true, true, false);
|
||||
if (0 == dao.count(User.class)) {
|
||||
FileSqlManager fm = new FileSqlManager("init_system_h2.sql");
|
||||
List<Sql> sqlList = fm.createCombo(fm.keys());
|
||||
dao.execute(sqlList.toArray(new Sql[sqlList.size()]));
|
||||
List<User> userList = dao.query(User.class, null);
|
||||
for (User user : userList) {
|
||||
RandomNumberGenerator rng = new SecureRandomNumberGenerator();
|
||||
String salt = rng.nextBytes().toBase64();
|
||||
String hashedPasswordBase64 = new Sha256Hash("123", salt, 1024).toBase64();
|
||||
user.setSalt(salt);
|
||||
user.setPassword(hashedPasswordBase64);
|
||||
dao.update(user);
|
||||
}
|
||||
}
|
||||
authorityService.initFormPackage("com.rekoe");
|
||||
projectConfigService.init();
|
||||
}
|
||||
}
|
|
@ -1,98 +0,0 @@
|
|||
package com.rekoe;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.shiro.crypto.RandomNumberGenerator;
|
||||
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
|
||||
import org.apache.shiro.crypto.hash.Sha256Hash;
|
||||
import org.nutz.boot.starter.freemarker.FreeMarkerConfigurer;
|
||||
import org.nutz.dao.Dao;
|
||||
import org.nutz.dao.impl.FileSqlManager;
|
||||
import org.nutz.dao.sql.Sql;
|
||||
import org.nutz.dao.util.Daos;
|
||||
import org.nutz.ioc.Ioc;
|
||||
import org.nutz.mvc.NutConfig;
|
||||
import org.nutz.mvc.Setup;
|
||||
import org.tmatesoft.svn.core.SVNCommitInfo;
|
||||
import org.tmatesoft.svn.core.SVNException;
|
||||
import org.tmatesoft.svn.core.SVNURL;
|
||||
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
|
||||
import org.tmatesoft.svn.core.wc.SVNClientManager;
|
||||
import org.tmatesoft.svn.core.wc.SVNCommitClient;
|
||||
import org.tmatesoft.svn.core.wc.SVNWCUtil;
|
||||
|
||||
import com.rekoe.domain.Pj;
|
||||
import com.rekoe.domain.PjGrUsr;
|
||||
import com.rekoe.domain.ProjectConfig;
|
||||
import com.rekoe.domain.User;
|
||||
import com.rekoe.domain.Usr;
|
||||
import com.rekoe.service.AuthorityService;
|
||||
import com.rekoe.service.ProjectConfigService;
|
||||
|
||||
import freemarker.template.Configuration;
|
||||
|
||||
/**
|
||||
* @author 科技㊣²º¹³ <br />
|
||||
* 2014年2月3日 下午4:48:45<br />
|
||||
* http://www.rekoe.com <br />
|
||||
* QQ:5382211
|
||||
*/
|
||||
public class MvcSetup implements Setup {
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
@Override
|
||||
public void init(NutConfig config) {
|
||||
Ioc ioc = config.getIoc();
|
||||
// 加载freemarker自定义标签 自定义宏路径
|
||||
ioc.get(Configuration.class).setAutoImports(new HashMap<String, String>(2) {
|
||||
{
|
||||
put("p", "/ftl/pony/index.ftl");
|
||||
put("s", "/ftl/spring.ftl");
|
||||
}
|
||||
});
|
||||
ioc.get(FreeMarkerConfigurer.class, "mapTags");
|
||||
Dao dao = ioc.get(Dao.class);
|
||||
dao.create(PjGrUsr.class, false);
|
||||
// dao.clear(OAuthUser.class);
|
||||
Daos.createTablesInPackage(dao, User.class.getPackage().getName(), false);
|
||||
Daos.migration(dao, Usr.class, true, true, false);
|
||||
Daos.migration(dao, Pj.class, true, true, false);
|
||||
Daos.migration(dao, ProjectConfig.class, true, true, false);
|
||||
if (0 == dao.count(User.class)) {
|
||||
FileSqlManager fm = new FileSqlManager("init_system_h2.sql");
|
||||
List<Sql> sqlList = fm.createCombo(fm.keys());
|
||||
dao.execute(sqlList.toArray(new Sql[sqlList.size()]));
|
||||
List<User> userList = dao.query(User.class, null);
|
||||
for (User user : userList) {
|
||||
RandomNumberGenerator rng = new SecureRandomNumberGenerator();
|
||||
String salt = rng.nextBytes().toBase64();
|
||||
String hashedPasswordBase64 = new Sha256Hash("123", salt, 1024).toBase64();
|
||||
user.setSalt(salt);
|
||||
user.setPassword(hashedPasswordBase64);
|
||||
dao.update(user);
|
||||
}
|
||||
}
|
||||
ioc.get(AuthorityService.class).initFormPackage("com.rekoe");
|
||||
ioc.get(ProjectConfigService.class).init();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager("admin", "john");
|
||||
SVNClientManager manager = SVNClientManager.newInstance();
|
||||
manager.setAuthenticationManager(authManager);
|
||||
SVNCommitClient commitClient = SVNClientManager.newInstance().getCommitClient();
|
||||
try {
|
||||
SVNCommitInfo info = commitClient.doMkDir(new SVNURL[] { SVNURL.parseURIEncoded("http://192.168.3.127/repository/koux/trunk") }, "commitMessage", null, true);
|
||||
long newRevision = info.getNewRevision();
|
||||
System.out.println(newRevision);
|
||||
} catch (SVNException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy(NutConfig config) {
|
||||
|
||||
}
|
||||
}
|
|
@ -1,165 +0,0 @@
|
|||
package com.rekoe.cms.socialauth;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.brickred.socialauth.AbstractProvider;
|
||||
import org.brickred.socialauth.AuthProvider;
|
||||
import org.brickred.socialauth.Contact;
|
||||
import org.brickred.socialauth.Permission;
|
||||
import org.brickred.socialauth.Profile;
|
||||
import org.brickred.socialauth.exception.AccessTokenExpireException;
|
||||
import org.brickred.socialauth.exception.SocialAuthException;
|
||||
import org.brickred.socialauth.exception.UserDeniedPermissionException;
|
||||
import org.brickred.socialauth.oauthstrategy.OAuthStrategyBase;
|
||||
import org.brickred.socialauth.util.AccessGrant;
|
||||
import org.brickred.socialauth.util.OAuthConfig;
|
||||
import org.brickred.socialauth.util.Response;
|
||||
import org.brickred.socialauth.util.SocialAuthUtil;
|
||||
import org.nutz.lang.Lang;
|
||||
import org.nutz.log.Log;
|
||||
import org.nutz.log.Logs;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public abstract class AbstractOAuthProvider extends AbstractProvider implements AuthProvider {
|
||||
|
||||
private static final Log log = Logs.get();
|
||||
|
||||
protected Permission scope;
|
||||
protected OAuthConfig config;
|
||||
protected Profile userProfile;
|
||||
protected AccessGrant accessGrant;
|
||||
protected OAuthStrategyBase authenticationStrategy;
|
||||
|
||||
protected static String[] AllPerms;
|
||||
protected static String[] AuthPerms;
|
||||
protected static Map<String, String> ENDPOINTS = new HashMap<String, String>();
|
||||
|
||||
protected abstract String getPlatform();
|
||||
public AbstractOAuthProvider(OAuthConfig providerConfig) throws Exception {
|
||||
this.config = providerConfig;
|
||||
}
|
||||
|
||||
public String getLoginRedirectURL(final String successUrl) throws Exception {
|
||||
return authenticationStrategy.getLoginRedirectURL(successUrl);
|
||||
}
|
||||
|
||||
public Profile verifyResponse(HttpServletRequest httpReq) throws Exception {
|
||||
Map<String, String> params = SocialAuthUtil.getRequestParametersMap(httpReq);
|
||||
return doVerifyResponse(params);
|
||||
}
|
||||
|
||||
public Profile verifyResponse(Map<String, String> params) throws Exception {
|
||||
return doVerifyResponse(params);
|
||||
}
|
||||
|
||||
protected Profile doVerifyResponse(final Map<String, String> requestParams) throws Exception {
|
||||
log.info("Retrieving Access Token in verify response function");
|
||||
if (requestParams.get("error_reason") != null && "user_denied".equals(requestParams.get("error_reason"))) {
|
||||
throw new UserDeniedPermissionException();
|
||||
}
|
||||
accessGrant = authenticationStrategy.verifyResponse(requestParams, verifyResponseMethod());
|
||||
if (accessGrant != null) {
|
||||
log.debug("Obtaining user profile");
|
||||
Profile proFile = authLogin();
|
||||
return proFile;
|
||||
} else {
|
||||
throw new SocialAuthException("Access token not found");
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract Profile authLogin() throws Exception;
|
||||
|
||||
public Response api(final String url, final String methodType, final Map<String, String> params, final Map<String, String> headerParams, final String body) throws Exception {
|
||||
try {
|
||||
return authenticationStrategy.executeFeed(url, methodType, params, headerParams, body);
|
||||
} catch (Exception e) {
|
||||
throw new SocialAuthException("Error while making request to URL : " + url, e);
|
||||
}
|
||||
}
|
||||
|
||||
public List<Contact> getContactList() throws Exception {
|
||||
throw Lang.makeThrow(SocialAuthException.class, "Get contact list is not implemented for %s", getPlatform());
|
||||
}
|
||||
|
||||
public void logout() {
|
||||
accessGrant = null;
|
||||
authenticationStrategy.logout();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPermission(Permission permission) {
|
||||
this.scope = permission;
|
||||
authenticationStrategy.setPermission(this.scope);
|
||||
authenticationStrategy.setScope(getScope());
|
||||
}
|
||||
|
||||
public Profile getUserProfile() throws Exception {
|
||||
return userProfile;
|
||||
}
|
||||
|
||||
public AccessGrant getAccessGrant() {
|
||||
return accessGrant;
|
||||
}
|
||||
|
||||
public String getProviderId() {
|
||||
return config.getId();
|
||||
}
|
||||
|
||||
protected String getScope() {
|
||||
StringBuffer result = new StringBuffer();
|
||||
String arr[] = null;
|
||||
if (Permission.AUTHENTICATE_ONLY.equals(scope)) {
|
||||
arr = AuthPerms;
|
||||
} else if (Permission.CUSTOM.equals(scope) && config.getCustomPermissions() != null) {
|
||||
arr = config.getCustomPermissions().split(",");
|
||||
} else {
|
||||
arr = AllPerms;
|
||||
}
|
||||
if (arr.length > 0)
|
||||
result.append(arr[0]);
|
||||
for (int i = 1; i < arr.length; i++) {
|
||||
result.append(",").append(arr[i]);
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
protected String verifyResponseMethod() {
|
||||
return "GET";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAccessGrant(AccessGrant accessGrant) throws AccessTokenExpireException, SocialAuthException {
|
||||
this.accessGrant = accessGrant;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response updateStatus(String arg0) throws Exception {
|
||||
throw Lang.makeThrow(SocialAuthException.class, "Update Status is not implemented for %s", getPlatform());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response uploadImage(String arg0, String arg1, InputStream arg2) throws Exception {
|
||||
throw Lang.makeThrow(SocialAuthException.class, "Update Image is not implemented for %s", getPlatform());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected OAuthStrategyBase getOauthStrategy() {
|
||||
return authenticationStrategy;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<String> getPluginsList() {
|
||||
List<String> list = new ArrayList<String>();
|
||||
if (config.getRegisteredPlugins() != null && config.getRegisteredPlugins().length > 0) {
|
||||
list.addAll(Arrays.asList(config.getRegisteredPlugins()));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
|
@ -1,92 +0,0 @@
|
|||
package com.rekoe.cms.socialauth.qq;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.brickred.socialauth.Profile;
|
||||
import org.brickred.socialauth.exception.SocialAuthException;
|
||||
import org.brickred.socialauth.oauthstrategy.OAuth2;
|
||||
import org.brickred.socialauth.util.Constants;
|
||||
import org.brickred.socialauth.util.OAuthConfig;
|
||||
import org.brickred.socialauth.util.Response;
|
||||
import org.nutz.json.Json;
|
||||
import org.nutz.log.Log;
|
||||
import org.nutz.log.Logs;
|
||||
|
||||
import com.rekoe.cms.socialauth.AbstractOAuthProvider;
|
||||
|
||||
/**
|
||||
* 实现QQ帐号登录,OAuth2
|
||||
*
|
||||
* @author wendal
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class QQAuthProvider extends AbstractOAuthProvider {
|
||||
|
||||
private final static Log log = Logs.get();
|
||||
private String PROFILE_URL= "https://graph.qq.com/oauth2.0/me";
|
||||
static {
|
||||
ENDPOINTS.put(Constants.OAUTH_AUTHORIZATION_URL, "https://graph.qq.com/oauth2.0/authorize");
|
||||
ENDPOINTS.put(Constants.OAUTH_ACCESS_TOKEN_URL, "https://graph.qq.com/oauth2.0/token");
|
||||
AllPerms = new String[] { "get_user_info", "get_info" };
|
||||
AuthPerms = new String[] { "get_user_info", "get_info" };
|
||||
}
|
||||
|
||||
public QQAuthProvider(final OAuthConfig providerConfig) throws Exception {
|
||||
super(providerConfig);
|
||||
authenticationStrategy = new OAuth2(config, ENDPOINTS);
|
||||
authenticationStrategy.setPermission(scope);
|
||||
authenticationStrategy.setScope(getScope());
|
||||
}
|
||||
|
||||
protected Profile authLogin() throws Exception {
|
||||
String presp;
|
||||
try {
|
||||
Response response = authenticationStrategy.executeFeed(PROFILE_URL);
|
||||
presp = response.getResponseBodyAsString(Constants.ENCODING);
|
||||
if (presp != null) {
|
||||
presp = presp.trim().intern();
|
||||
if (presp.startsWith("callback(") && presp.endsWith(");")) {
|
||||
presp = presp.substring(presp.indexOf("{"), presp.indexOf("}") + 1);
|
||||
Map<String, String> map = Json.fromJsonAsMap(String.class, presp);
|
||||
if (map.get("openid") != null) {
|
||||
Profile p = new Profile();
|
||||
p.setValidatedId(map.get("openid")); // QQ定义的
|
||||
p.setProviderId(getProviderId());
|
||||
userProfile = p;
|
||||
try {
|
||||
Map<String, String> params = new HashMap<String, String>();
|
||||
params.put("format", "json");
|
||||
params.put("openid", map.get("openid"));
|
||||
params.put("oauth_consumer_key", config.get_consumerKey());
|
||||
response = authenticationStrategy.executeFeed("https://graph.qq.com/user/get_user_info", "GET", params, null, null);
|
||||
presp = response.getResponseBodyAsString(Constants.ENCODING);
|
||||
Map<String, String> user_info = Json.fromJsonAsMap(String.class, presp);
|
||||
boolean isRight = NumberUtils.toInt(user_info.get("ret"), -1) == 0;
|
||||
if (isRight) { // 获取成功
|
||||
if (user_info.get("nickname") != null)
|
||||
p.setDisplayName(user_info.get("nickname"));
|
||||
if (user_info.get("figureurl") != null)
|
||||
p.setProfileImageURL(user_info.get("figureurl"));
|
||||
if (user_info.get("gender") != null)
|
||||
p.setGender(user_info.get("gender"));
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log.error(e);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new SocialAuthException("QQ Error : " + presp);
|
||||
} catch (Exception e) {
|
||||
throw new SocialAuthException("Error while getting profile from " + PROFILE_URL, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getPlatform() {
|
||||
return "QQ";
|
||||
}
|
||||
}
|
|
@ -1,126 +0,0 @@
|
|||
package com.rekoe.cms.socialauth.qqweibo;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.brickred.socialauth.Profile;
|
||||
import org.brickred.socialauth.exception.ServerDataException;
|
||||
import org.brickred.socialauth.exception.SocialAuthException;
|
||||
import org.brickred.socialauth.exception.UserDeniedPermissionException;
|
||||
import org.brickred.socialauth.oauthstrategy.OAuth1;
|
||||
import org.brickred.socialauth.oauthstrategy.OAuthStrategyBase;
|
||||
import org.brickred.socialauth.util.Constants;
|
||||
import org.brickred.socialauth.util.OAuthConfig;
|
||||
import org.brickred.socialauth.util.Response;
|
||||
import org.nutz.json.Json;
|
||||
import org.nutz.log.Log;
|
||||
import org.nutz.log.Logs;
|
||||
|
||||
import com.rekoe.cms.socialauth.AbstractOAuthProvider;
|
||||
|
||||
/**
|
||||
* 实现腾讯微博帐号登录,OAuth1
|
||||
*
|
||||
* @author wendal
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class QQWeiboAuthProvider extends AbstractOAuthProvider {
|
||||
|
||||
private static final Log log = Logs.get();
|
||||
private final String PROFILE_URL = "http://open.t.qq.com/api/user/info?format=json";
|
||||
public QQWeiboAuthProvider(final OAuthConfig providerConfig) throws Exception {
|
||||
super(providerConfig);
|
||||
ENDPOINTS.put(Constants.OAUTH_REQUEST_TOKEN_URL, "https://open.t.qq.com/cgi-bin/request_token");
|
||||
ENDPOINTS.put(Constants.OAUTH_AUTHORIZATION_URL, "https://open.t.qq.com/cgi-bin/authorize");
|
||||
ENDPOINTS.put(Constants.OAUTH_ACCESS_TOKEN_URL, "https://open.t.qq.com/cgi-bin/access_token");
|
||||
AllPerms = new String[] {};
|
||||
AuthPerms = new String[] {};
|
||||
authenticationStrategy = new OAuth1(config, ENDPOINTS);
|
||||
authenticationStrategy.setPermission(scope);
|
||||
authenticationStrategy.setScope(getScope());
|
||||
}
|
||||
|
||||
protected Profile doVerifyResponse(final Map<String, String> requestParams) throws Exception {
|
||||
log.info("Retrieving Access Token in verify response function");
|
||||
if (requestParams.get("error_reason") != null && "user_denied".equals(requestParams.get("error_reason"))) {
|
||||
throw new UserDeniedPermissionException();
|
||||
}
|
||||
accessGrant = authenticationStrategy.verifyResponse(requestParams, verifyResponseMethod());
|
||||
|
||||
if (accessGrant != null) {
|
||||
log.debug("Obtaining user profile");
|
||||
// try {
|
||||
// String presp =
|
||||
// authenticationStrategy.executeFeed(PROFILE_URL).getResponseBodyAsString("utf8");
|
||||
// System.out.println(Json.toJson(Json.fromJson(presp)));
|
||||
// } catch (Throwable e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
Profile p = new Profile();
|
||||
p.setValidatedId(requestParams.get("openid"));
|
||||
p.setProviderId(getProviderId());
|
||||
userProfile = p;
|
||||
return p;
|
||||
} else {
|
||||
throw new SocialAuthException("Access token not found");
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected Profile authLogin() throws Exception {
|
||||
String presp;
|
||||
try {
|
||||
Response response = authenticationStrategy.executeFeed(PROFILE_URL);
|
||||
presp = response.getResponseBodyAsString(Constants.ENCODING);
|
||||
} catch (Exception e) {
|
||||
throw new SocialAuthException("Error while getting profile from " + PROFILE_URL, e);
|
||||
}
|
||||
try {
|
||||
// System.out.println("User Profile : " + presp);
|
||||
Map<String, Object> data = Json.fromJson(Map.class, presp);
|
||||
if (!"ok".equals(data.get("msg")))
|
||||
throw new SocialAuthException("Error: " + presp);
|
||||
if (userProfile == null)
|
||||
userProfile = new Profile();
|
||||
data = (Map<String, Object>) data.get("data");
|
||||
userProfile.setValidatedId(data.get("uid").toString());
|
||||
return userProfile;
|
||||
} catch (Exception ex) {
|
||||
throw new ServerDataException("Failed to parse the user profile json : " + presp, ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response updateStatus(String arg0) throws Exception {
|
||||
log.warn("WARNING: Not implemented for QQAuthProvider");
|
||||
throw new SocialAuthException("Update Status is not implemented for QQAuthProvider");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response uploadImage(String arg0, String arg1, InputStream arg2) throws Exception {
|
||||
log.warn("WARNING: Not implemented for QQAuthProvider");
|
||||
throw new SocialAuthException("Upload Image is not implemented for QQAuthProvider");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected OAuthStrategyBase getOauthStrategy() {
|
||||
return authenticationStrategy;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<String> getPluginsList() {
|
||||
List<String> list = new ArrayList<String>();
|
||||
if (config.getRegisteredPlugins() != null && config.getRegisteredPlugins().length > 0) {
|
||||
list.addAll(Arrays.asList(config.getRegisteredPlugins()));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getPlatform() {
|
||||
return "qqweibo";
|
||||
}
|
||||
}
|
|
@ -3,44 +3,23 @@ package com.rekoe.module;
|
|||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.shiro.SecurityUtils;
|
||||
import org.apache.shiro.authc.AuthenticationException;
|
||||
import org.apache.shiro.authc.ExcessiveAttemptsException;
|
||||
import org.apache.shiro.authc.IncorrectCredentialsException;
|
||||
import org.apache.shiro.authc.LockedAccountException;
|
||||
import org.apache.shiro.authc.UnknownAccountException;
|
||||
import org.apache.shiro.authz.annotation.RequiresAuthentication;
|
||||
import org.apache.shiro.subject.Subject;
|
||||
import org.apache.shiro.util.ThreadContext;
|
||||
import org.brickred.socialauth.AuthProvider;
|
||||
import org.brickred.socialauth.Profile;
|
||||
import org.brickred.socialauth.SocialAuthConfig;
|
||||
import org.brickred.socialauth.SocialAuthManager;
|
||||
import org.brickred.socialauth.exception.SocialAuthException;
|
||||
import org.brickred.socialauth.util.SocialAuthUtil;
|
||||
import org.nutz.boot.starter.freemarker.FreeMarkerConfigurer;
|
||||
import org.nutz.boot.starter.freemarker.FreemarkerView;
|
||||
import org.nutz.ioc.loader.annotation.Inject;
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.lang.Encoding;
|
||||
import org.nutz.lang.Files;
|
||||
import org.nutz.lang.Lang;
|
||||
import org.nutz.lang.stream.NullInputStream;
|
||||
import org.nutz.mvc.View;
|
||||
import org.nutz.mvc.annotation.At;
|
||||
import org.nutz.mvc.annotation.Ok;
|
||||
import org.nutz.mvc.view.ForwardView;
|
||||
import org.nutz.mvc.view.ServerRedirectView;
|
||||
import org.nutz.mvc.view.ViewWrapper;
|
||||
|
||||
import com.rekoe.common.Message;
|
||||
import com.rekoe.shiro.realm.OAuthToken;
|
||||
|
||||
/**
|
||||
* @author 科技㊣²º¹³ <br />
|
||||
|
@ -90,41 +69,6 @@ public class OauthLoginAct {
|
|||
SecurityUtils.getSubject().logout();
|
||||
}
|
||||
|
||||
/* 无需做链接,这是OpenID的回调地址 */
|
||||
@At("/login/?/callback")
|
||||
public View returnPoint(String providerId, HttpServletRequest request, HttpSession session) throws Exception {
|
||||
SocialAuthManager manager = (SocialAuthManager) session.getAttribute("openid.manager");
|
||||
if (manager == null)
|
||||
throw new SocialAuthException("Not manager found!");
|
||||
session.removeAttribute("openid.manager"); // 防止重复登录的可能性
|
||||
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
|
||||
Subject currentUser = SecurityUtils.getSubject();
|
||||
boolean rname = false;
|
||||
try {
|
||||
AuthProvider provider = manager.connect(paramsMap);
|
||||
Profile p = provider.getUserProfile();
|
||||
ThreadContext.bind(currentUser);
|
||||
OAuthToken token = new OAuthToken(p, Lang.getIP(request), session);
|
||||
currentUser.login(token);
|
||||
rname = token.isRname();
|
||||
} catch (UnknownAccountException uae) {
|
||||
return new ViewWrapper(new FreemarkerView(freeMarkerConfigurer, "template/admin/common/error"), Message.error("帐号不存在", request));
|
||||
} catch (IncorrectCredentialsException ice) {
|
||||
return new ViewWrapper(new FreemarkerView(freeMarkerConfigurer, "template/admin/common/error"), Message.error("证书验证失败", request));
|
||||
} catch (LockedAccountException lae) {
|
||||
// "帐号已被锁定"
|
||||
return new ViewWrapper(new FreemarkerView(freeMarkerConfigurer, "template/admin/common/error"), Message.error("帐号未被授权,请联系管理员", request));
|
||||
} catch (ExcessiveAttemptsException eae) {
|
||||
return new ViewWrapper(new FreemarkerView(freeMarkerConfigurer, "template/admin/common/error"), Message.error("尝试的次数太多", request));
|
||||
} catch (AuthenticationException ae) {
|
||||
return new ViewWrapper(new ForwardView("/admin/index"), ae.getMessage());
|
||||
}
|
||||
if (rname) {
|
||||
return new ViewWrapper(new ServerRedirectView("/admin/register.rk"), null);
|
||||
}
|
||||
return new ViewWrapper(new ServerRedirectView("/admin/main.rk"), null);
|
||||
}
|
||||
|
||||
private SocialAuthConfig config;
|
||||
|
||||
public void init() throws Exception {
|
||||
|
|
|
@ -22,9 +22,6 @@ public class EmailServiceImpl implements EmailService {
|
|||
@Inject("refer:$ioc")
|
||||
protected Ioc ioc;
|
||||
|
||||
@Inject
|
||||
private Configuration configuration;
|
||||
|
||||
@Inject
|
||||
private FreeMarkerConfigurer freeMarkerConfigurer;
|
||||
|
||||
|
@ -49,7 +46,7 @@ public class EmailServiceImpl implements EmailService {
|
|||
private String processTemplateIntoString(String templateFile, Map<String, Object> root) {
|
||||
try {
|
||||
String path = "template" + File.separator + "admin" + File.separator + "common" + File.separator + templateFile + freeMarkerConfigurer.getSuffix();
|
||||
Template template = configuration.getTemplate(path);
|
||||
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(path);
|
||||
template.setEncoding("UTF-8");
|
||||
java.io.StringWriter writer = new java.io.StringWriter();
|
||||
template.process(root, writer);
|
||||
|
|
|
@ -1,29 +0,0 @@
|
|||
package com.rekoe.shiro.freemarker;
|
||||
|
||||
import freemarker.template.SimpleHash;
|
||||
|
||||
/**
|
||||
* Shortcut for injecting the tags into Freemarker
|
||||
*
|
||||
* <p>Usage: cfg.setSharedVeriable("shiro", new ShiroTags());</p>
|
||||
*/
|
||||
public class ShiroTags extends SimpleHash {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = -6249359256658075586L;
|
||||
|
||||
public ShiroTags() {
|
||||
put("authenticated", new AuthenticatedTag());
|
||||
put("guest", new GuestTag());
|
||||
put("hasAnyRoles", new HasAnyRolesTag());
|
||||
put("hasPermission", new HasPermissionTag());
|
||||
put("hasAnyPermission", new HasAnyPermissionTag());
|
||||
put("hasRole", new HasRoleTag());
|
||||
put("lacksPermission", new LacksPermissionTag());
|
||||
put("lacksRole", new LacksRoleTag());
|
||||
put("notAuthenticated", new NotAuthenticatedTag());
|
||||
put("principal", new PrincipalTag());
|
||||
put("user", new UserTag());
|
||||
}
|
||||
}
|
|
@ -1,79 +0,0 @@
|
|||
package com.rekoe.shiro.realm;
|
||||
|
||||
import org.apache.shiro.authz.AuthorizationInfo;
|
||||
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
||||
import org.apache.shiro.cache.Cache;
|
||||
import org.apache.shiro.realm.AuthorizingRealm;
|
||||
import org.apache.shiro.subject.PrincipalCollection;
|
||||
import org.apache.shiro.subject.SimplePrincipalCollection;
|
||||
import org.nutz.castor.Castors;
|
||||
import org.nutz.ioc.Ioc;
|
||||
import org.nutz.lang.Lang;
|
||||
import org.nutz.mvc.Mvcs;
|
||||
|
||||
import com.rekoe.domain.Role;
|
||||
import com.rekoe.domain.User;
|
||||
import com.rekoe.service.RoleService;
|
||||
import com.rekoe.service.UserService;
|
||||
|
||||
/**
|
||||
* @author 科技㊣²º¹³<br />
|
||||
* 2014年2月3日 下午4:48:45 <br />
|
||||
* http://www.rekoe.com QQ:5382211
|
||||
*/
|
||||
public abstract class AbstractNutAuthoRealm extends AuthorizingRealm {
|
||||
|
||||
private UserService userService;
|
||||
private RoleService roleService;
|
||||
|
||||
protected UserService getUserService() {
|
||||
if (Lang.isEmpty(userService)) {
|
||||
Ioc ioc = Mvcs.getIoc();
|
||||
userService = ioc.get(UserService.class);
|
||||
}
|
||||
return userService;
|
||||
}
|
||||
|
||||
protected RoleService getRoleService() {
|
||||
if (Lang.isEmpty(roleService)) {
|
||||
Ioc ioc = Mvcs.getIoc();
|
||||
roleService = ioc.get(RoleService.class);
|
||||
}
|
||||
return roleService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新用户授权信息缓存.
|
||||
*/
|
||||
public void clearCachedAuthorizationInfo(String principal) {
|
||||
SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
|
||||
clearCachedAuthorizationInfo(principals);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有用户授权信息缓存.
|
||||
*/
|
||||
public void clearAllCachedAuthorizationInfo() {
|
||||
Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
|
||||
if (cache != null) {
|
||||
for (Object key : cache.keys()) {
|
||||
cache.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
|
||||
*/
|
||||
@Override
|
||||
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
|
||||
Object object = principals.getPrimaryPrincipal();
|
||||
User user = Castors.me().castTo(object, User.class);
|
||||
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
|
||||
info.addRoles(getUserService().getRoleNameList(user));
|
||||
for (Role role : user.getRoles()) {
|
||||
info.addStringPermissions(getRoleService().getPermissionNameList(role));
|
||||
}
|
||||
return info;
|
||||
}
|
||||
}
|
|
@ -1,49 +0,0 @@
|
|||
package com.rekoe.shiro.realm;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.shiro.authc.AuthenticationInfo;
|
||||
import org.apache.shiro.authc.AuthenticationToken;
|
||||
import org.apache.shiro.authc.DisabledAccountException;
|
||||
import org.apache.shiro.authc.LockedAccountException;
|
||||
import org.apache.shiro.authc.SimpleAuthenticationInfo;
|
||||
import org.brickred.socialauth.Profile;
|
||||
import org.nutz.castor.Castors;
|
||||
import org.nutz.lang.Lang;
|
||||
|
||||
import com.rekoe.domain.User;
|
||||
|
||||
/**
|
||||
* @author 科技㊣²º¹³<br />
|
||||
* 2014年2月3日 下午<br/>
|
||||
* 4:48:45<br/>
|
||||
* http://www.rekoe.com <br />
|
||||
* QQ:5382211
|
||||
*/
|
||||
public class NutAuthoDaoRealm extends AbstractNutAuthoRealm {
|
||||
|
||||
public NutAuthoDaoRealm() {
|
||||
setAuthenticationTokenClass(OAuthToken.class);
|
||||
}
|
||||
|
||||
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws DisabledAccountException {
|
||||
OAuthToken oauthToken = Castors.me().castTo(token, OAuthToken.class);
|
||||
Profile credential = oauthToken.getCredentials();
|
||||
String openid = credential.getValidatedId();
|
||||
User user = getUserService().fetchByOpenID(openid);
|
||||
if (Lang.isEmpty(user)) {
|
||||
String nickName = StringUtils.defaultString(credential.getDisplayName(), openid);
|
||||
String providerid = credential.getProviderId();
|
||||
user = getUserService().initUser(nickName, openid, providerid, oauthToken.getAddr());
|
||||
} else {
|
||||
if (user.isLocked()) {
|
||||
throw Lang.makeThrow(LockedAccountException.class, "Account [ %s ] is locked.", user.getName());
|
||||
}
|
||||
getUserService().loadRolePermission(user);
|
||||
}
|
||||
oauthToken.setRname(user.isSystem());
|
||||
oauthToken.setUserId(openid);
|
||||
SimpleAuthenticationInfo account = new SimpleAuthenticationInfo(user, credential, getName());
|
||||
oauthToken.getSession().setAttribute("me", user);
|
||||
return account;
|
||||
}
|
||||
}
|
|
@ -1,74 +0,0 @@
|
|||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package com.rekoe.shiro.realm;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.shiro.authc.AuthenticationToken;
|
||||
import org.brickred.socialauth.Profile;
|
||||
|
||||
/**
|
||||
* This class represents a token for an OAuth authentication process (OAuth
|
||||
* credential + user identifier after authentication).
|
||||
*
|
||||
* @author Jerome Leleu
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public final class OAuthToken implements AuthenticationToken {
|
||||
|
||||
private static final long serialVersionUID = 3376624432421737333L;
|
||||
private Profile credential;
|
||||
private String userId;
|
||||
private String addr;
|
||||
private HttpSession session;
|
||||
private boolean rname;
|
||||
public OAuthToken(Profile credential, String addr,HttpSession session) {
|
||||
this.credential = credential;
|
||||
this.addr = addr;
|
||||
this.session = session;
|
||||
}
|
||||
|
||||
public void setUserId(String userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Object getPrincipal() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public Profile getCredentials() {
|
||||
return credential;
|
||||
}
|
||||
|
||||
public String getAddr() {
|
||||
return addr;
|
||||
}
|
||||
|
||||
public HttpSession getSession() {
|
||||
return session;
|
||||
}
|
||||
|
||||
public boolean isRname() {
|
||||
return rname;
|
||||
}
|
||||
|
||||
public void setRname(boolean rname) {
|
||||
this.rname = rname;
|
||||
}
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
package com.rekoe.shiro.realm;
|
||||
|
||||
public enum RealmAuthorizationType {
|
||||
|
||||
USER, PROFILE;
|
||||
}
|
|
@ -9,21 +9,42 @@ import org.apache.shiro.authc.LockedAccountException;
|
|||
import org.apache.shiro.authc.SimpleAuthenticationInfo;
|
||||
import org.apache.shiro.authc.UnknownAccountException;
|
||||
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||
import org.apache.shiro.authz.AuthorizationInfo;
|
||||
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
||||
import org.apache.shiro.subject.PrincipalCollection;
|
||||
import org.apache.shiro.util.ByteSource;
|
||||
import org.nutz.castor.Castors;
|
||||
import org.nutz.integration.shiro.AbstractSimpleAuthorizingRealm;
|
||||
import org.nutz.ioc.loader.annotation.Inject;
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.lang.Lang;
|
||||
import org.nutz.lang.Strings;
|
||||
|
||||
import com.rekoe.domain.Role;
|
||||
import com.rekoe.domain.User;
|
||||
import com.rekoe.exception.CreateUserSaltException;
|
||||
import com.rekoe.service.RoleService;
|
||||
import com.rekoe.service.UserService;
|
||||
|
||||
/**
|
||||
* @author 科技㊣²º¹³<br />
|
||||
* 2014年2月3日 下午4:48:45<br />
|
||||
* http://www.rekoe.com<br />
|
||||
* QQ:5382211
|
||||
*/
|
||||
public class UsernamePasswordRealm extends AbstractNutAuthoRealm {
|
||||
@IocBean(name = "shiroRealm", create = "_init")
|
||||
public class UsernamePasswordRealm extends AbstractSimpleAuthorizingRealm {
|
||||
|
||||
@Inject
|
||||
private UserService userService;
|
||||
@Inject
|
||||
private RoleService roleService;
|
||||
|
||||
@Inject
|
||||
private org.apache.shiro.cache.CacheManager shiroCacheManager;
|
||||
|
||||
public void _init() {
|
||||
setCacheManager(shiroCacheManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(AuthenticationToken token) {
|
||||
return token instanceof UsernamePasswordToken;
|
||||
}
|
||||
|
||||
public UsernamePasswordRealm() {
|
||||
setAuthenticationTokenClass(UsernamePasswordToken.class);
|
||||
|
@ -35,7 +56,7 @@ public class UsernamePasswordRealm extends AbstractNutAuthoRealm {
|
|||
if (StringUtils.isBlank(accountName)) {
|
||||
throw Lang.makeThrow(AuthenticationException.class, "Account is empty");
|
||||
}
|
||||
User user = getUserService().fetchByName(authcToken.getUsername());
|
||||
User user = userService.fetchByName(authcToken.getUsername());
|
||||
if (Lang.isEmpty(user)) {
|
||||
throw Lang.makeThrow(UnknownAccountException.class, "Account [ %s ] not found", authcToken.getUsername());
|
||||
}
|
||||
|
@ -46,10 +67,22 @@ public class UsernamePasswordRealm extends AbstractNutAuthoRealm {
|
|||
if (Strings.isBlank(userSalt)) {
|
||||
throw Lang.makeThrow(CreateUserSaltException.class, "Account [ %s ] is not set PassWord", authcToken.getUsername());
|
||||
}
|
||||
getUserService().loadRolePermission(user);
|
||||
userService.loadRolePermission(user);
|
||||
ByteSource salt = ByteSource.Util.bytes(user.getSalt());
|
||||
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
|
||||
info.setCredentialsSalt(salt);
|
||||
return info;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
|
||||
Object object = principals.getPrimaryPrincipal();
|
||||
User user = Castors.me().castTo(object, User.class);
|
||||
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
|
||||
info.addRoles(userService.getRoleNameList(user));
|
||||
for (Role role : user.getRoles()) {
|
||||
info.addStringPermissions(roleService.getPermissionNameList(role));
|
||||
}
|
||||
return info;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,421 +0,0 @@
|
|||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package com.rekoe.shiro.web;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.shiro.util.StringUtils;
|
||||
import org.apache.shiro.web.servlet.Cookie;
|
||||
import org.nutz.lang.Lang;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Default {@link Cookie Cookie} implementation. 'HttpOnly' is supported out of
|
||||
* the box, even on Servlet {@code 2.4} and {@code 2.5} container
|
||||
* implementations, using raw header writing logic and not
|
||||
* {@link javax.servlet.http.Cookie javax.servlet.http.Cookie} objects (which
|
||||
* only has 'HttpOnly' support in Servlet {@code 2.6} specifications and above).
|
||||
*
|
||||
* @since 1.0
|
||||
*/
|
||||
public class SimpleCookie implements Cookie {
|
||||
|
||||
/**
|
||||
* {@code -1}, indicating the cookie should expire when the browser closes.
|
||||
*/
|
||||
public static final int DEFAULT_MAX_AGE = -1;
|
||||
|
||||
/**
|
||||
* {@code -1} indicating that no version property should be set on the
|
||||
* cookie.
|
||||
*/
|
||||
public static final int DEFAULT_VERSION = -1;
|
||||
|
||||
// These constants are protected on purpose so that the test case can use
|
||||
// them
|
||||
protected static final String NAME_VALUE_DELIMITER = "=";
|
||||
protected static final String ATTRIBUTE_DELIMITER = "; ";
|
||||
protected static final long DAY_MILLIS = 86400000; // 1 day = 86,400,000
|
||||
// milliseconds
|
||||
protected static final String GMT_TIME_ZONE_ID = "GMT";
|
||||
protected static final String COOKIE_DATE_FORMAT_STRING = "EEE, dd-MMM-yyyy HH:mm:ss z";
|
||||
|
||||
protected static final String COOKIE_HEADER_NAME = "Set-Cookie";
|
||||
protected static final String PATH_ATTRIBUTE_NAME = "Path";
|
||||
protected static final String EXPIRES_ATTRIBUTE_NAME = "Expires";
|
||||
protected static final String MAXAGE_ATTRIBUTE_NAME = "Max-Age";
|
||||
protected static final String DOMAIN_ATTRIBUTE_NAME = "Domain";
|
||||
protected static final String VERSION_ATTRIBUTE_NAME = "Version";
|
||||
protected static final String COMMENT_ATTRIBUTE_NAME = "Comment";
|
||||
protected static final String SECURE_ATTRIBUTE_NAME = "Secure";
|
||||
protected static final String HTTP_ONLY_ATTRIBUTE_NAME = "HttpOnly";
|
||||
|
||||
private static final transient Logger log = LoggerFactory.getLogger(SimpleCookie.class);
|
||||
|
||||
private String name;
|
||||
private String value;
|
||||
private String comment;
|
||||
private String domain;
|
||||
private String path;
|
||||
private int maxAge;
|
||||
private int version;
|
||||
private boolean secure;
|
||||
private boolean httpOnly;
|
||||
|
||||
public SimpleCookie() {
|
||||
this.maxAge = DEFAULT_MAX_AGE;
|
||||
this.version = DEFAULT_VERSION;
|
||||
this.httpOnly = true; // most of the cookies ever used by Shiro should
|
||||
// be as secure as possible.
|
||||
}
|
||||
|
||||
public SimpleCookie(String name) {
|
||||
this();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public SimpleCookie(Cookie cookie) {
|
||||
this.name = cookie.getName();
|
||||
this.value = cookie.getValue();
|
||||
this.comment = cookie.getComment();
|
||||
this.domain = cookie.getDomain();
|
||||
this.path = cookie.getPath();
|
||||
this.maxAge = Math.max(DEFAULT_MAX_AGE, cookie.getMaxAge());
|
||||
this.version = Math.max(DEFAULT_VERSION, cookie.getVersion());
|
||||
this.secure = cookie.isSecure();
|
||||
this.httpOnly = cookie.isHttpOnly();
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalArgumentException("Name cannot be null/empty.");
|
||||
}
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getComment() {
|
||||
return comment;
|
||||
}
|
||||
|
||||
public void setComment(String comment) {
|
||||
this.comment = comment;
|
||||
}
|
||||
|
||||
public String getDomain() {
|
||||
return domain;
|
||||
}
|
||||
|
||||
public void setDomain(String domain) {
|
||||
this.domain = domain;
|
||||
}
|
||||
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
public void setPath(String path) {
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
public int getMaxAge() {
|
||||
return maxAge;
|
||||
}
|
||||
|
||||
public void setMaxAge(int maxAge) {
|
||||
this.maxAge = Math.max(DEFAULT_MAX_AGE, maxAge);
|
||||
}
|
||||
|
||||
public int getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(int version) {
|
||||
this.version = Math.max(DEFAULT_VERSION, version);
|
||||
}
|
||||
|
||||
public boolean isSecure() {
|
||||
return secure;
|
||||
}
|
||||
|
||||
public void setSecure(boolean secure) {
|
||||
this.secure = secure;
|
||||
}
|
||||
|
||||
public boolean isHttpOnly() {
|
||||
return httpOnly;
|
||||
}
|
||||
|
||||
public void setHttpOnly(boolean httpOnly) {
|
||||
this.httpOnly = httpOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Cookie's calculated path setting. If the
|
||||
* {@link javax.servlet.http.Cookie#getPath() path} is {@code null}, then
|
||||
* the {@code request}'s
|
||||
* {@link javax.servlet.http.HttpServletRequest#getContextPath() context
|
||||
* path} will be returned. If getContextPath() is the empty string or null
|
||||
* then the ROOT_PATH constant is returned.
|
||||
*
|
||||
* @param request
|
||||
* the incoming HttpServletRequest
|
||||
* @return the path to be used as the path when the cookie is created or
|
||||
* removed
|
||||
*/
|
||||
private String calculatePath(HttpServletRequest request) {
|
||||
String path = StringUtils.clean(getPath());
|
||||
if (!StringUtils.hasText(path)) {
|
||||
if (Lang.isEmpty(request)) {
|
||||
return ROOT_PATH;
|
||||
}
|
||||
path = StringUtils.clean(request.getContextPath());
|
||||
}
|
||||
// fix for http://issues.apache.org/jira/browse/SHIRO-9:
|
||||
if (path == null) {
|
||||
path = ROOT_PATH;
|
||||
}
|
||||
log.trace("calculated path: {}", path);
|
||||
return path;
|
||||
}
|
||||
|
||||
public void saveTo(HttpServletRequest request, HttpServletResponse response) {
|
||||
|
||||
String name = getName();
|
||||
String value = getValue();
|
||||
String comment = getComment();
|
||||
String domain = getDomain();
|
||||
String path = calculatePath(request);
|
||||
int maxAge = getMaxAge();
|
||||
int version = getVersion();
|
||||
boolean secure = isSecure();
|
||||
boolean httpOnly = isHttpOnly();
|
||||
|
||||
addCookieHeader(response, name, value, comment, domain, path, maxAge, version, secure, httpOnly);
|
||||
}
|
||||
|
||||
private void addCookieHeader(HttpServletResponse response, String name, String value, String comment, String domain, String path, int maxAge, int version, boolean secure, boolean httpOnly) {
|
||||
|
||||
String headerValue = buildHeaderValue(name, value, comment, domain, path, maxAge, version, secure, httpOnly);
|
||||
response.addHeader(COOKIE_HEADER_NAME, headerValue);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Added HttpServletResponse Cookie [{}]", headerValue);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* This implementation followed the grammar defined here for convenience: <a
|
||||
* href=
|
||||
* "http://github.com/abarth/http-state/blob/master/notes/2009-11-07-Yui-Naruse.txt"
|
||||
* >Cookie grammar</a>.
|
||||
*
|
||||
* @return the 'Set-Cookie' header value for this cookie instance.
|
||||
*/
|
||||
|
||||
protected String buildHeaderValue(String name, String value, String comment, String domain, String path, int maxAge, int version, boolean secure, boolean httpOnly) {
|
||||
|
||||
if (!StringUtils.hasText(name)) {
|
||||
throw new IllegalStateException("Cookie name cannot be null/empty.");
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder(name).append(NAME_VALUE_DELIMITER);
|
||||
|
||||
if (StringUtils.hasText(value)) {
|
||||
sb.append(value);
|
||||
}
|
||||
|
||||
appendComment(sb, comment);
|
||||
appendDomain(sb, domain);
|
||||
appendPath(sb, path);
|
||||
appendExpires(sb, maxAge);
|
||||
appendVersion(sb, version);
|
||||
appendSecure(sb, secure);
|
||||
appendHttpOnly(sb, httpOnly);
|
||||
|
||||
return sb.toString();
|
||||
|
||||
}
|
||||
|
||||
private void appendComment(StringBuilder sb, String comment) {
|
||||
if (StringUtils.hasText(comment)) {
|
||||
sb.append(ATTRIBUTE_DELIMITER);
|
||||
sb.append(COMMENT_ATTRIBUTE_NAME).append(NAME_VALUE_DELIMITER).append(comment);
|
||||
}
|
||||
}
|
||||
|
||||
private void appendDomain(StringBuilder sb, String domain) {
|
||||
if (StringUtils.hasText(domain)) {
|
||||
sb.append(ATTRIBUTE_DELIMITER);
|
||||
sb.append(DOMAIN_ATTRIBUTE_NAME).append(NAME_VALUE_DELIMITER).append(domain);
|
||||
}
|
||||
}
|
||||
|
||||
private void appendPath(StringBuilder sb, String path) {
|
||||
if (StringUtils.hasText(path)) {
|
||||
sb.append(ATTRIBUTE_DELIMITER);
|
||||
sb.append(PATH_ATTRIBUTE_NAME).append(NAME_VALUE_DELIMITER).append(path);
|
||||
}
|
||||
}
|
||||
|
||||
private void appendExpires(StringBuilder sb, int maxAge) {
|
||||
// if maxAge is negative, cookie should should expire when browser
|
||||
// closes
|
||||
// Don't write the maxAge cookie value if it's negative - at least on
|
||||
// Firefox it'll cause the
|
||||
// cookie to be deleted immediately
|
||||
// Write the expires header used by older browsers, but may be
|
||||
// unnecessary
|
||||
// and it is not by the spec, see http://www.faqs.org/rfcs/rfc2965.html
|
||||
// TODO consider completely removing the following
|
||||
if (maxAge >= 0) {
|
||||
sb.append(ATTRIBUTE_DELIMITER);
|
||||
sb.append(MAXAGE_ATTRIBUTE_NAME).append(NAME_VALUE_DELIMITER).append(maxAge);
|
||||
sb.append(ATTRIBUTE_DELIMITER);
|
||||
Date expires;
|
||||
if (maxAge == 0) {
|
||||
// delete the cookie by specifying a time in the past (1 day
|
||||
// ago):
|
||||
expires = new Date(System.currentTimeMillis() - DAY_MILLIS);
|
||||
} else {
|
||||
// Value is in seconds. So take 'now' and add that many seconds,
|
||||
// and that's our expiration date:
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.add(Calendar.SECOND, maxAge);
|
||||
expires = cal.getTime();
|
||||
}
|
||||
String formatted = toCookieDate(expires);
|
||||
sb.append(EXPIRES_ATTRIBUTE_NAME).append(NAME_VALUE_DELIMITER).append(formatted);
|
||||
}
|
||||
}
|
||||
|
||||
private void appendVersion(StringBuilder sb, int version) {
|
||||
if (version > DEFAULT_VERSION) {
|
||||
sb.append(ATTRIBUTE_DELIMITER);
|
||||
sb.append(VERSION_ATTRIBUTE_NAME).append(NAME_VALUE_DELIMITER).append(version);
|
||||
}
|
||||
}
|
||||
|
||||
private void appendSecure(StringBuilder sb, boolean secure) {
|
||||
if (secure) {
|
||||
sb.append(ATTRIBUTE_DELIMITER);
|
||||
sb.append(SECURE_ATTRIBUTE_NAME); // No value for this attribute
|
||||
}
|
||||
}
|
||||
|
||||
private void appendHttpOnly(StringBuilder sb, boolean httpOnly) {
|
||||
if (httpOnly) {
|
||||
sb.append(ATTRIBUTE_DELIMITER);
|
||||
sb.append(HTTP_ONLY_ATTRIBUTE_NAME); // No value for this attribute
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a date into a cookie date compatible string (Netscape's
|
||||
* specification).
|
||||
*
|
||||
* @param date
|
||||
* the date to format
|
||||
* @return an HTTP 1.0/1.1 Cookie compatible date string (GMT-based).
|
||||
*/
|
||||
private static String toCookieDate(Date date) {
|
||||
TimeZone tz = TimeZone.getTimeZone(GMT_TIME_ZONE_ID);
|
||||
DateFormat fmt = new SimpleDateFormat(COOKIE_DATE_FORMAT_STRING, Locale.US);
|
||||
fmt.setTimeZone(tz);
|
||||
return fmt.format(date);
|
||||
}
|
||||
|
||||
public void removeFrom(HttpServletRequest request, HttpServletResponse response) {
|
||||
String name = getName();
|
||||
String value = DELETED_COOKIE_VALUE;
|
||||
String comment = null; // don't need to add extra size to the response -
|
||||
// comments are irrelevant for deletions
|
||||
String domain = getDomain();
|
||||
String path = calculatePath(request);
|
||||
int maxAge = 0; // always zero for deletion
|
||||
int version = getVersion();
|
||||
boolean secure = isSecure();
|
||||
boolean httpOnly = false; // no need to add the extra text, plus the
|
||||
// value 'deleteMe' is not sensitive at all
|
||||
|
||||
addCookieHeader(response, name, value, comment, domain, path, maxAge, version, secure, httpOnly);
|
||||
|
||||
log.trace("Removed '{}' cookie by setting maxAge=0", name);
|
||||
}
|
||||
|
||||
public String readValue(HttpServletRequest request, HttpServletResponse ignored) {
|
||||
String name = getName();
|
||||
String value = null;
|
||||
javax.servlet.http.Cookie cookie = getCookie(request, name);
|
||||
if (cookie != null) {
|
||||
value = cookie.getValue();
|
||||
log.debug("Found '{}' cookie value [{}]", name, value);
|
||||
} else {
|
||||
log.trace("No '{}' cookie value", name);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the cookie with the given name from the request or {@code null}
|
||||
* if no cookie with that name could be found.
|
||||
*
|
||||
* @param request
|
||||
* the current executing http request.
|
||||
* @param cookieName
|
||||
* the name of the cookie to find and return.
|
||||
* @return the cookie with the given name from the request or {@code null}
|
||||
* if no cookie with that name could be found.
|
||||
*/
|
||||
private static javax.servlet.http.Cookie getCookie(HttpServletRequest request, String cookieName) {
|
||||
if (request == null) {
|
||||
return null;
|
||||
}
|
||||
javax.servlet.http.Cookie cookies[] = request.getCookies();
|
||||
if (cookies != null) {
|
||||
for (javax.servlet.http.Cookie cookie : cookies) {
|
||||
if (cookie.getName().equals(cookieName)) {
|
||||
return cookie;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
|
@ -4,6 +4,7 @@ import java.io.IOException;
|
|||
import java.io.Writer;
|
||||
import java.util.Map;
|
||||
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.lang.Times;
|
||||
|
||||
import freemarker.core.Environment;
|
||||
|
@ -16,6 +17,7 @@ import freemarker.template.TemplateModel;
|
|||
* 执行时间标签
|
||||
*
|
||||
*/
|
||||
@IocBean(name = "currentTime")
|
||||
public class CurrentTimeDirective implements TemplateDirectiveModel {
|
||||
|
||||
@SuppressWarnings({ "rawtypes" })
|
||||
|
|
|
@ -5,6 +5,7 @@ import java.io.Writer;
|
|||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.lang.Lang;
|
||||
|
||||
import com.rekoe.utils.DirectiveUtils;
|
||||
|
@ -19,14 +20,14 @@ import freemarker.template.TemplateModel;
|
|||
/**
|
||||
* HTML文本提取并截断
|
||||
*/
|
||||
@IocBean(name = "htmlCut")
|
||||
public class HtmlCutDirective implements TemplateDirectiveModel {
|
||||
public static final String PARAM_S = "s";
|
||||
public static final String PARAM_LEN = "len";
|
||||
public static final String PARAM_APPEND = "append";
|
||||
|
||||
@SuppressWarnings({"unchecked","rawtypes"})
|
||||
public void execute(Environment env, Map params, TemplateModel[] loopVars,
|
||||
TemplateDirectiveBody body) throws TemplateException, IOException {
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
|
||||
String s = DirectiveUtils.getString(PARAM_S, params);
|
||||
Integer len = DirectiveUtils.getInt(PARAM_LEN, params);
|
||||
String append = DirectiveUtils.getString(PARAM_APPEND, params);
|
||||
|
|
|
@ -6,6 +6,8 @@ import java.util.HashMap;
|
|||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
|
||||
import com.rekoe.utils.DirectiveUtils;
|
||||
|
||||
import freemarker.core.Environment;
|
||||
|
@ -14,9 +16,11 @@ import freemarker.template.TemplateDirectiveModel;
|
|||
import freemarker.template.TemplateException;
|
||||
import freemarker.template.TemplateModel;
|
||||
|
||||
@IocBean(name = "pagination")
|
||||
public class PaginationDirective implements TemplateDirectiveModel {
|
||||
|
||||
private static final String PATTERN = "pattern";
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
@Override
|
||||
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
|
||||
|
|
|
@ -5,6 +5,7 @@ import java.io.Writer;
|
|||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.lang.Lang;
|
||||
|
||||
import com.rekoe.domain.Permission;
|
||||
|
@ -17,6 +18,7 @@ import freemarker.template.TemplateDirectiveModel;
|
|||
import freemarker.template.TemplateException;
|
||||
import freemarker.template.TemplateModel;
|
||||
|
||||
@IocBean(name = "permission")
|
||||
public class PermissionDirective implements TemplateDirectiveModel {
|
||||
|
||||
private final static String ERROR_ID = "-1";
|
||||
|
|
|
@ -5,6 +5,7 @@ import java.io.Writer;
|
|||
import java.text.DecimalFormat;
|
||||
import java.util.Map;
|
||||
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.mvc.NutConfigException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
@ -21,6 +22,7 @@ import freemarker.template.TemplateNumberModel;
|
|||
* 执行时间标签
|
||||
*
|
||||
*/
|
||||
@IocBean(name = "process")
|
||||
public class ProcessTimeDirective implements TemplateDirectiveModel {
|
||||
private static final Logger log = LoggerFactory.getLogger(ProcessTimeDirective.class);
|
||||
private static final DecimalFormat FORMAT = new DecimalFormat("0.000");
|
||||
|
|
|
@ -5,6 +5,7 @@ import java.io.Writer;
|
|||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.nutz.ioc.loader.annotation.IocBean;
|
||||
import org.nutz.lang.Times;
|
||||
|
||||
import com.rekoe.utils.DirectiveUtils;
|
||||
|
@ -18,6 +19,7 @@ import freemarker.template.TemplateModel;
|
|||
/**
|
||||
* 格式化date
|
||||
*/
|
||||
@IocBean(name = "timeFormat")
|
||||
public class TimeFormatDirective implements TemplateDirectiveModel {
|
||||
public static final String PARAM_TIME = "time";
|
||||
public static final String PARAM_FORMAT = "format";
|
||||
|
@ -30,8 +32,9 @@ public class TimeFormatDirective implements TemplateDirectiveModel {
|
|||
String formatTime = Times.format(format, Times.D(NumberUtils.toLong(time)));
|
||||
out.append(formatTime);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String formatTime = Times.format("yyyy-MM", Times.now());//Times.D("1389076676271"));
|
||||
String formatTime = Times.format("yyyy-MM", Times.now());// Times.D("1389076676271"));
|
||||
System.out.print(formatTime);
|
||||
System.out.println(Times.D(1389076676271L));
|
||||
}
|
||||
|
|
|
@ -1,74 +0,0 @@
|
|||
var ioc = {
|
||||
conf : {
|
||||
type : "org.nutz.ioc.impl.PropertiesProxy",
|
||||
fields : {
|
||||
paths : "conf.properties"
|
||||
}
|
||||
},
|
||||
dataSource : {
|
||||
type : "com.alibaba.druid.pool.DruidDataSource",
|
||||
events : {
|
||||
create : "init",
|
||||
depose : 'close'
|
||||
},
|
||||
fields : {
|
||||
url : {
|
||||
java : "$conf.get('db.url', 'jdbc:mysql://127.0.0.1:3306/platform?useUnicode=true&characterEncoding=utf-8')"
|
||||
},
|
||||
username : {
|
||||
java : "$conf.get('db.username', 'root')"
|
||||
},
|
||||
password : {
|
||||
java : "$conf.get('db.password', 'root')"
|
||||
},
|
||||
maxActive : {
|
||||
java : "$conf.getInt('db.maxActive', 20)"
|
||||
},
|
||||
validationQuery : "SELECT 'x'",
|
||||
testWhileIdle : true,
|
||||
testOnBorrow : false,
|
||||
testOnReturn : false,
|
||||
filters : "mergeStat",
|
||||
connectionProperties : "druid.stat.slowSqlMillis=1000"
|
||||
}
|
||||
},
|
||||
|
||||
dao : {
|
||||
type : "org.nutz.dao.impl.NutDao",
|
||||
args : [ {
|
||||
refer : "dataSource"
|
||||
} ],
|
||||
fields : {
|
||||
executor : {
|
||||
refer : "cacheExecutor"
|
||||
}
|
||||
}
|
||||
},
|
||||
cacheExecutor : {
|
||||
type : "org.nutz.plugins.cache.dao.CachedNutDaoExecutor",
|
||||
fields : {
|
||||
cacheProvider : {
|
||||
refer : "cacheProvider"
|
||||
},
|
||||
cachedTableNames : [ "system_permission", "permission_category",
|
||||
"system_role", "system_user", "system_server",
|
||||
" system_user_server", "system_user_role", "verify_server",
|
||||
"official_server", "server_history", "platform_user",
|
||||
"cdkey_category", "project_config" ],
|
||||
enableWhenTrans : false, // 事务作用域内不启用缓存,默认也是false
|
||||
db : "MYSQL"
|
||||
}
|
||||
},
|
||||
cacheProvider : {
|
||||
type : "org.nutz.plugins.cache.dao.impl.provider.EhcacheDaoCacheProvider",
|
||||
fields : {
|
||||
cacheManager : {
|
||||
refer : "cacheManager"
|
||||
}
|
||||
// 引用ehcache.js中定义的CacheManager
|
||||
},
|
||||
events : {
|
||||
create : "init"
|
||||
}
|
||||
}
|
||||
};
|
|
@ -1,14 +0,0 @@
|
|||
var ioc = {
|
||||
cacheManager : {
|
||||
type : "net.sf.ehcache.CacheManager",
|
||||
factory : "net.sf.ehcache.CacheManager#getCacheManager",
|
||||
args : ["rk_platform"] // 对应shiro.ini中指定的ehcache.xml中定义的name
|
||||
}
|
||||
/*
|
||||
// 如果不需要shiro初始化的Ehcache, 使用下面的方式配置
|
||||
cacheManager : {
|
||||
type : "net.sf.ehcache.CacheManager",
|
||||
factory : "net.sf.ehcache.CacheManager#create"
|
||||
}
|
||||
*/
|
||||
};
|
|
@ -1,61 +0,0 @@
|
|||
var ioc = {
|
||||
shiroTags : {
|
||||
type : "com.rekoe.shiro.freemarker.ShiroTags"
|
||||
},
|
||||
permissionResolver : {
|
||||
type : "org.apache.shiro.authz.permission.WildcardPermissionResolver"
|
||||
},
|
||||
permissionShiro : {
|
||||
type : "com.rekoe.web.freemarker.PermissionShiroFreemarker",
|
||||
args : [ {
|
||||
refer : "permissionResolver"
|
||||
} ]
|
||||
},
|
||||
permission : {
|
||||
type : "com.rekoe.web.freemarker.PermissionDirective"
|
||||
},
|
||||
process : {
|
||||
type : "com.rekoe.web.freemarker.ProcessTimeDirective"
|
||||
},
|
||||
currentTime : {
|
||||
type : "com.rekoe.web.freemarker.CurrentTimeDirective"
|
||||
},
|
||||
htmlCut : {
|
||||
type : "com.rekoe.web.freemarker.HtmlCutDirective"
|
||||
},
|
||||
pagination : {
|
||||
type : "com.rekoe.web.freemarker.PaginationDirective"
|
||||
},
|
||||
timeFormat : {
|
||||
type : "com.rekoe.web.freemarker.TimeFormatDirective"
|
||||
},
|
||||
mapTags : {
|
||||
factory : "$freeMarkerConfigurer#addTags",
|
||||
args : [ {
|
||||
'shiro' : {
|
||||
refer : 'shiroTags'
|
||||
},
|
||||
'perm_chow' : {
|
||||
refer : 'permissionShiro'
|
||||
},
|
||||
'cms_perm' : {
|
||||
refer : 'permission'
|
||||
},
|
||||
'process_time' : {
|
||||
refer : 'process'
|
||||
},
|
||||
'pagination' : {
|
||||
refer : 'pagination'
|
||||
},
|
||||
'htmlCut' : {
|
||||
refer : 'htmlCut'
|
||||
},
|
||||
'timeFormat' : {
|
||||
refer : 'timeFormat'
|
||||
},
|
||||
'currentTime' : {
|
||||
refer : 'currentTime'
|
||||
}
|
||||
} ]
|
||||
}
|
||||
};
|
|
@ -1,17 +0,0 @@
|
|||
var ioc={
|
||||
emailAuthenticator : {
|
||||
type : "org.apache.commons.mail.DefaultAuthenticator",
|
||||
args : [{java:"$conf.get('mail.UserName')"}, {java:"$conf.get('mail.Password')"}]
|
||||
},
|
||||
htmlEmail : {
|
||||
type : "org.apache.commons.mail.ImageHtmlEmail",
|
||||
singleton : false,
|
||||
fields : {
|
||||
hostName : {java:"$conf.get('mail.HostName')"},
|
||||
smtpPort : {java:"$conf.get('mail.SmtpPort')"},
|
||||
authenticator : {refer:"emailAuthenticator"},
|
||||
SSLOnConnect : {java:"$conf.get('mail.SSLOnConnect')"},
|
||||
from : {java:"$conf.get('mail.From')"}
|
||||
}
|
||||
}
|
||||
};
|
|
@ -1,33 +0,0 @@
|
|||
var uploadIoc = {
|
||||
tmpFilePool : {
|
||||
type : 'org.nutz.filepool.NutFilePool', // 临时文件最大个数为 1000 个
|
||||
args : [ {
|
||||
java : "$conf.get('upload.temp','~/tmp')"
|
||||
}, 1000 ]
|
||||
},
|
||||
uploadFileContext : {
|
||||
type : 'org.nutz.mvc.upload.UploadingContext',
|
||||
singleton : true,
|
||||
args : [ {
|
||||
refer : 'tmpFilePool'
|
||||
} ],
|
||||
fields : {
|
||||
// 是否忽略空文件, 默认为 false
|
||||
ignoreNull : true,
|
||||
// 单个文件最大尺寸(大约的值,单位为字节,即 1048576 为 1M)
|
||||
maxFileSize : {
|
||||
java : "$conf.getInt('upload.maxFileSize',5048576)"
|
||||
},
|
||||
nameFilter : {
|
||||
java : "$conf.get('upload.nameFilter','^(.+[.])(doc|docx|ppt|pptx|pdf|jpg|gif)$')"
|
||||
}
|
||||
}
|
||||
},
|
||||
upload : {
|
||||
type : 'org.nutz.mvc.upload.UploadAdaptor',
|
||||
singleton : true,
|
||||
args : [ {
|
||||
refer : 'uploadFileContext'
|
||||
} ]
|
||||
}
|
||||
};
|
|
@ -1,9 +1,11 @@
|
|||
log4j.rootLogger=DEBUG,A1,file
|
||||
log4j.rootLogger=INFO,A1,file
|
||||
log4j.logger.velocity_log=INFO
|
||||
log4j.category.org.nutz=DEBUG,A1,file
|
||||
log4j.category.org.nutz.dao=DEBUG
|
||||
log4j.category.org.nutz.ioc=INFO
|
||||
log4j.category.org.nutz.plugins.ngrok=OFF
|
||||
log4j.category.org.nutz.mvc=DEBUG
|
||||
log4j.category.org.eclipse.jetty=OFF
|
||||
log4j.category.org.apache.shiro=INFO
|
||||
log4j.category.org.brickred.socialauth=INFO
|
||||
log4j.category.org.apache.commons=INFO
|
||||
|
|
Loading…
Reference in New Issue