use of org.apache.shiro.session.Session in project graylog2-server by Graylog2.
the class SessionsResource method newSession.
@POST
@ApiOperation(value = "Create a new session", notes = "This request creates a new session for a user or reactivates an existing session: the equivalent of logging in.")
@NoAuditEvent("dispatches audit events in the method body")
public SessionResponse newSession(@Context ContainerRequestContext requestContext, @ApiParam(name = "Login request", value = "Username and credentials", required = true) @Valid @NotNull SessionCreateRequest createRequest) {
final SecurityContext securityContext = requestContext.getSecurityContext();
if (!(securityContext instanceof ShiroSecurityContext)) {
throw new InternalServerErrorException("Unsupported SecurityContext class, this is a bug!");
}
final ShiroSecurityContext shiroSecurityContext = (ShiroSecurityContext) securityContext;
// we treat the BASIC auth username as the sessionid
final String sessionId = shiroSecurityContext.getUsername();
// pretend that we had session id before
Serializable id = null;
if (sessionId != null && !sessionId.isEmpty()) {
id = sessionId;
}
final String remoteAddrFromRequest = RestTools.getRemoteAddrFromRequest(grizzlyRequest, trustedSubnets);
final Subject subject = new Subject.Builder().sessionId(id).host(remoteAddrFromRequest).buildSubject();
ThreadContext.bind(subject);
final Session s = subject.getSession();
try {
subject.login(new UsernamePasswordToken(createRequest.username(), createRequest.password()));
final User user = userService.load(createRequest.username());
if (user != null) {
long timeoutInMillis = user.getSessionTimeoutMs();
s.setTimeout(timeoutInMillis);
} else {
// set a sane default. really we should be able to load the user from above.
s.setTimeout(TimeUnit.HOURS.toMillis(8));
}
s.touch();
// save subject in session, otherwise we can't get the username back in subsequent requests.
((DefaultSecurityManager) SecurityUtils.getSecurityManager()).getSubjectDAO().save(subject);
} catch (AuthenticationException e) {
LOG.info("Invalid username or password for user \"{}\"", createRequest.username());
} catch (UnknownSessionException e) {
subject.logout();
}
if (subject.isAuthenticated()) {
id = s.getId();
final Map<String, Object> auditEventContext = ImmutableMap.of("session_id", id, "remote_address", remoteAddrFromRequest);
auditEventSender.success(AuditActor.user(createRequest.username()), SESSION_CREATE, auditEventContext);
// TODO is the validUntil attribute even used by anyone yet?
return SessionResponse.create(new DateTime(s.getLastAccessTime(), DateTimeZone.UTC).plus(s.getTimeout()).toDate(), id.toString());
} else {
final Map<String, Object> auditEventContext = ImmutableMap.of("remote_address", remoteAddrFromRequest);
auditEventSender.failure(AuditActor.user(createRequest.username()), SESSION_CREATE, auditEventContext);
throw new NotAuthorizedException("Invalid username or password", "Basic realm=\"Graylog Server session\"");
}
}
use of org.apache.shiro.session.Session in project ddf by codice.
the class TestWorkspaceQueryService method testRun.
@SuppressWarnings("unchecked")
@Test
public void testRun() throws SchedulerException, UnsupportedQueryException, SourceUnavailableException, FederationException {
String workspaceId = "3";
QueryUpdateSubscriber queryUpdateSubscriber = mock(QueryUpdateSubscriber.class);
WorkspaceService workspaceService = mock(WorkspaceService.class);
CatalogFramework catalogFramework = mock(CatalogFramework.class);
FilterBuilder filterBuilder = mock(FilterBuilder.class);
Scheduler scheduler = mock(Scheduler.class);
when(scheduler.getContext()).thenReturn(mock(SchedulerContext.class));
Supplier<Optional<Scheduler>> schedulerSupplier = () -> Optional.of(scheduler);
SecurityService securityService = new SecurityService() {
@Override
public Subject getSystemSubject() {
return mock(Subject.class);
}
@Override
public Map<String, Serializable> addSystemSubject(Map<String, Serializable> properties) {
return properties;
}
};
FilterService filterService = mock(FilterService.class);
when(filterService.getModifiedDateFilter(any())).thenReturn(mock(Filter.class));
when(filterBuilder.anyOf(Mockito.any(Filter.class))).thenReturn(mock(Or.class));
when(filterBuilder.allOf(Mockito.<Filter>anyVararg())).thenReturn(mock(And.class));
WorkspaceQueryServiceImpl workspaceQueryServiceImpl = new WorkspaceQueryServiceImpl(queryUpdateSubscriber, workspaceService, catalogFramework, filterBuilder, schedulerSupplier, securityService, filterService);
workspaceQueryServiceImpl.setQueryTimeInterval(60);
String ecql = "area( Polygon((10 10, 20 10, 20 20, 10 10)) ) BETWEEN 10000 AND 30000";
WorkspaceMetacardImpl workspaceMetacard = mock(WorkspaceMetacardImpl.class);
when(workspaceMetacard.getId()).thenReturn(workspaceId);
QueryMetacardImpl queryMetacardWithSource = mock(QueryMetacardImpl.class);
when(queryMetacardWithSource.getSources()).thenReturn(Collections.singletonList("SomeSource"));
when(queryMetacardWithSource.getCql()).thenReturn(ecql);
Attribute id1 = mock(Attribute.class);
when(id1.getValue()).thenReturn("1");
when(queryMetacardWithSource.getAttribute(Metacard.ID)).thenReturn(id1);
QueryMetacardImpl queryMetacardWithoutSource = mock(QueryMetacardImpl.class);
when(queryMetacardWithoutSource.getSources()).thenReturn(Collections.emptyList());
when(queryMetacardWithoutSource.getCql()).thenReturn(ecql);
Attribute id2 = mock(Attribute.class);
when(id2.getValue()).thenReturn("2");
when(queryMetacardWithoutSource.getAttribute(Metacard.ID)).thenReturn(id2);
Map<String, Pair<WorkspaceMetacardImpl, List<QueryMetacardImpl>>> queryMetacards = Collections.singletonMap(id2.getValue().toString(), new ImmutablePair<>(workspaceMetacard, Arrays.asList(queryMetacardWithSource, queryMetacardWithoutSource)));
when(workspaceService.getQueryMetacards()).thenReturn(queryMetacards);
long hitCount1 = 10;
long hitCount2 = 20;
QueryResponse queryResponse = mock(QueryResponse.class);
when(queryResponse.getHits()).thenReturn(hitCount1).thenReturn(hitCount2);
when(catalogFramework.query(any())).thenReturn(queryResponse);
workspaceQueryServiceImpl.setSubject(new Subject() {
@Override
public boolean isGuest() {
return false;
}
@Override
public Object getPrincipal() {
return null;
}
@Override
public PrincipalCollection getPrincipals() {
return null;
}
@Override
public boolean isPermitted(String s) {
return false;
}
@Override
public boolean isPermitted(Permission permission) {
return false;
}
@Override
public boolean[] isPermitted(String... strings) {
return new boolean[0];
}
@Override
public boolean[] isPermitted(List<Permission> list) {
return new boolean[0];
}
@Override
public boolean isPermittedAll(String... strings) {
return false;
}
@Override
public boolean isPermittedAll(Collection<Permission> collection) {
return false;
}
@Override
public void checkPermission(String s) throws AuthorizationException {
}
@Override
public void checkPermission(Permission permission) throws AuthorizationException {
}
@Override
public void checkPermissions(String... strings) throws AuthorizationException {
}
@Override
public void checkPermissions(Collection<Permission> collection) throws AuthorizationException {
}
@Override
public boolean hasRole(String s) {
return false;
}
@Override
public boolean[] hasRoles(List<String> list) {
return new boolean[0];
}
@Override
public boolean hasAllRoles(Collection<String> collection) {
return false;
}
@Override
public void checkRole(String s) throws AuthorizationException {
}
@Override
public void checkRoles(Collection<String> collection) throws AuthorizationException {
}
@Override
public void checkRoles(String... strings) throws AuthorizationException {
}
@Override
public void login(AuthenticationToken authenticationToken) throws AuthenticationException {
}
@Override
public boolean isAuthenticated() {
return false;
}
@Override
public boolean isRemembered() {
return false;
}
@Override
public Session getSession() {
return null;
}
@Override
public Session getSession(boolean b) {
return null;
}
@Override
public void logout() {
}
@Override
public <V> V execute(Callable<V> callable) throws ExecutionException {
try {
return callable.call();
} catch (Exception e) {
throw new ExecutionException(e);
}
}
@Override
public void execute(Runnable runnable) {
}
@Override
public <V> Callable<V> associateWith(Callable<V> callable) {
return null;
}
@Override
public Runnable associateWith(Runnable runnable) {
return null;
}
@Override
public void runAs(PrincipalCollection principalCollection) throws NullPointerException, IllegalStateException {
}
@Override
public boolean isRunAs() {
return false;
}
@Override
public PrincipalCollection getPreviousPrincipals() {
return null;
}
@Override
public PrincipalCollection releaseRunAs() {
return null;
}
});
workspaceQueryServiceImpl.setCronString("0 0 0 * * ?");
workspaceQueryServiceImpl.setQueryTimeoutMinutes(5L);
workspaceQueryServiceImpl.run();
ArgumentCaptor<Map> argumentCaptor = ArgumentCaptor.forClass(Map.class);
verify(queryUpdateSubscriber).notify(argumentCaptor.capture());
Map queryUpdateSubscriberArgumentRaw = argumentCaptor.getValue();
Map<String, Pair<WorkspaceMetacardImpl, Long>> queryUpdateSubscriberArgument = (Map<String, Pair<WorkspaceMetacardImpl, Long>>) queryUpdateSubscriberArgumentRaw;
assertThat(queryUpdateSubscriberArgument.get(workspaceId).getRight(), is(hitCount1 + hitCount2));
}
use of org.apache.shiro.session.Session in project tesla by linking12.
the class SessionService method forceLogout.
public boolean forceLogout(String sessionId) {
Session session = sessionDAO.readSession(sessionId);
session.setTimeout(0);
return true;
}
use of org.apache.shiro.session.Session in project vip by guangdada.
the class ShiroKit method setSessionAttr.
/**
* 设置shiro指定的sessionKey
*/
public static void setSessionAttr(String key, Object value) {
Session session = getSession();
session.setAttribute(key, value);
}
use of org.apache.shiro.session.Session in project Workload by amoxu.
the class FindPsw method getQuestion.
@RequestMapping(value = "/password/getQuestion", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
@ResponseBody
public String getQuestion(User user) throws Exception {
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
if (session.getAttribute("rand") == null || !session.getAttribute("rand").toString().equalsIgnoreCase(user.getMail())) {
return "{\"status\":1,\"msg\":\"请重新输入验证码!\"}";
}
User nUser = userService.findByName(user.getUser());
if (nUser != null) {
return "{\"status\":0,\"msg\":\"" + nUser.getQuestion() + "\"}";
} else {
return "{\"status\":1,\"msg\":\"请检查用户名!\"}";
}
}
Aggregations