supports(Class)   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
eloc 3
1
package unicon.matthews.security.auth.ajax;
2
3
import java.util.Collections;
4
import java.util.List;
5
6
import org.springframework.beans.factory.annotation.Autowired;
7
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
8
import org.springframework.security.authentication.AuthenticationProvider;
9
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
10
import org.springframework.security.core.Authentication;
11
import org.springframework.security.core.AuthenticationException;
12
import org.springframework.security.core.GrantedAuthority;
13
import org.springframework.security.core.authority.SimpleGrantedAuthority;
14
import org.springframework.stereotype.Component;
15
import org.springframework.util.Assert;
16
17
import unicon.matthews.Vocabulary;
18
import unicon.matthews.oneroster.Org;
19
import unicon.matthews.oneroster.exception.OrgNotFoundException;
20
import unicon.matthews.oneroster.service.OrgService;
21
import unicon.matthews.security.model.UserContext;
22
23
/**
24
 * 
25
 * @author vladimir.stankovic
26
 *
27
 * Aug 3, 2016
28
 */
29
@Component
30
public class AjaxAuthenticationProvider implements AuthenticationProvider {
31
    private final OrgService orgService;
32
33
    @Autowired
34
    public AjaxAuthenticationProvider(final OrgService orgService) {
35
        this.orgService = orgService;
36
    }
37
38
    @Override
39
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
40
        Assert.notNull(authentication, "No authentication data provided");
41
42
        String key = (String) authentication.getPrincipal();
43
        String secret = (String) authentication.getCredentials();
44
        
45
        Org org;
46
        try {
47
          org = orgService.findByApiKeyAndApiSecret(key, secret);
48
        } 
49
        catch (OrgNotFoundException e) {
50
          throw new AuthenticationCredentialsNotFoundException(e.getMessage());
51
        }
52
        List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_ORG_ADMIN"));        
53
        UserContext userContext = UserContext.create(org.getMetadata().get(Vocabulary.TENANT), org.getSourcedId(), authorities);        
54
        return new UsernamePasswordAuthenticationToken(userContext, null, userContext.getAuthorities());
55
    }
56
57
    @Override
58
    public boolean supports(Class<?> authentication) {
59
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
60
    }
61
}
62