Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
Max Mecklin
/
Moya
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 5fe73e18
authored
Mar 05, 2014
by
Tuomas Riihimäki
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Rest authentication.
1 parent
a49d4b80
Hide whitespace changes
Inline
Side-by-side
Showing
15 changed files
with
758 additions
and
92 deletions
MoyaAuthModulev4.jar
code/MoyaAuthModule/src/fi/codecrew/moya/MoyaLoginModule.java
code/MoyaAuthModule/src/fi/codecrew/moya/MoyaRealm.java
code/MoyaAuthModuleClient/src/fi/codecrew/moya/AuthenticationResult.java
code/MoyaAuthModuleClient/src/fi/codecrew/moya/MoyaRealmBeanRemote.java
code/MoyaBeans/ejbModule/fi/codecrew/moya/beans/JaasBean.java
code/MoyaBeans/ejbModule/fi/codecrew/moya/beans/RestBean.java
code/MoyaBeans/ejbModule/fi/codecrew/moya/facade/ApiApplicationFacade.java
code/MoyaBeans/ejbModule/fi/codecrew/moya/facade/ApiApplicationInstanceFacade.java
code/MoyaBeansClient/ejbModule/fi/codecrew/moya/beans/RestBeanLocal.java
code/MoyaDatabase/src/fi/codecrew/moya/model/ApiApplication.java
code/MoyaDatabase/src/fi/codecrew/moya/model/ApiApplicationInstance.java
code/MoyaUtilities/src/main/java/fi/codecrew/moya/enums/apps/SpecialPermission.java
code/MoyaWeb/src/fi/codecrew/moya/HostnameFilter.java
code/MoyaWeb/src/fi/codecrew/moya/rest/ApplicationRestView.java
MoyaAuthModulev4.jar
View file @
5fe73e1
No preview for this file type
code/MoyaAuthModule/src/fi/codecrew/moya/MoyaLoginModule.java
View file @
5fe73e1
...
...
@@ -86,13 +86,14 @@ public class MoyaLoginModule extends AppservPasswordLoginModule {
// Authenticate User
MoyaRealm
samplerealm
=
(
MoyaRealm
)
_currentRealm
;
if
(!
authbean
.
authenticate
(
_username
,
new
String
(
_passwd
)))
{
AuthenticationResult
authResult
=
authbean
.
authUsername
(
_username
,
new
String
(
_passwd
));
if
(
authResult
==
null
||
authResult
.
getUsername
()
==
null
)
{
// Login fails
throw
new
LoginException
((
new
StringBuilder
())
.
append
(
"moya realm:Login Failed for user "
)
.
append
(
_username
).
toString
());
}
_username
=
authResult
.
getUsername
();
// Login succeeds
log
((
new
StringBuilder
()).
append
(
"MoyaRealm:login succeeded for "
)
.
append
(
_username
).
toString
());
...
...
@@ -100,7 +101,7 @@ public class MoyaLoginModule extends AppservPasswordLoginModule {
// Get group names for the authenticated user from the Realm class
Enumeration
<
String
>
enumeration
=
null
;
try
{
enumeration
=
samplerealm
.
getGroupNames
(
_username
);
enumeration
=
samplerealm
.
getGroupNames
(
_username
,
authResult
.
getUsertype
()
);
}
catch
(
InvalidOperationException
invalidoperationexception
)
{
throw
new
LoginException
(
(
new
StringBuilder
())
...
...
code/MoyaAuthModule/src/fi/codecrew/moya/MoyaRealm.java
View file @
5fe73e1
...
...
@@ -127,4 +127,8 @@ public class MoyaRealm extends AppservRealm {
}
public
Enumeration
<
String
>
getGroupNames
(
String
username
,
String
usertype
)
throws
InvalidOperationException
,
NoSuchUserException
{
return
getAuthBean
().
getGroupNames
(
username
,
usertype
);
}
}
code/MoyaAuthModuleClient/src/fi/codecrew/moya/AuthenticationResult.java
0 → 100644
View file @
5fe73e1
package
fi
.
codecrew
.
moya
;
public
class
AuthenticationResult
{
private
String
username
=
null
;
private
String
usertype
=
null
;
public
String
getUsername
()
{
return
username
;
}
public
void
setUsername
(
String
username
)
{
this
.
username
=
username
;
}
public
String
getUsertype
()
{
return
usertype
;
}
public
void
setUsertype
(
String
usertype
)
{
this
.
usertype
=
usertype
;
}
}
code/MoyaAuthModuleClient/src/fi/codecrew/moya/MoyaRealmBeanRemote.java
View file @
5fe73e1
...
...
@@ -13,4 +13,8 @@ public interface MoyaRealmBeanRemote {
boolean
authenticate
(
String
_username
,
String
string
);
AuthenticationResult
authUsername
(
String
_username
,
String
string
);
Enumeration
<
String
>
getGroupNames
(
String
username
,
String
usertype
);
}
code/MoyaBeans/ejbModule/fi/codecrew/moya/beans/JaasBean.java
View file @
5fe73e1
...
...
@@ -11,18 +11,24 @@ import javax.ejb.Stateless;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
fi.codecrew.moya.AuthenticationResult
;
import
fi.codecrew.moya.MoyaRealmBeanRemote
;
import
fi.codecrew.moya.enums.BortalApplication
;
import
fi.codecrew.moya.enums.apps.IAppPermission
;
import
fi.codecrew.moya.enums.apps.SpecialPermission
;
import
fi.codecrew.moya.enums.apps.UserPermission
;
import
fi.codecrew.moya.facade.ApiApplicationFacade
;
import
fi.codecrew.moya.facade.ApiApplicationInstanceFacade
;
import
fi.codecrew.moya.facade.EventUserFacade
;
import
fi.codecrew.moya.facade.UserFacade
;
import
fi.codecrew.moya.model.ApiApplication
;
import
fi.codecrew.moya.model.ApiApplicationInstance
;
import
fi.codecrew.moya.model.ApplicationPermission
;
import
fi.codecrew.moya.model.EventUser
;
import
fi.codecrew.moya.model.LanEvent
;
import
fi.codecrew.moya.model.Role
;
import
fi.codecrew.moya.model.User
;
import
fi.codecrew.moya.utilities.PasswordFunctions
;
/**
* Session Bean implementation class SessionHandlerBean
...
...
@@ -48,6 +54,13 @@ public class JaasBean implements MoyaRealmBeanRemote {
@EJB
private
EventBeanLocal
eventbean
;
@EJB
private
RestBean
restbean
;
@EJB
private
ApiApplicationFacade
appfacade
;
@EJB
private
ApiApplicationInstanceFacade
appInstanceFacade
;
public
EventUser
tryLogin
(
String
username
,
String
password
)
{
EventUser
eventUser
=
eventUserFacade
.
findByLogin
(
username
.
trim
().
toLowerCase
());
...
...
@@ -97,14 +110,48 @@ public class JaasBean implements MoyaRealmBeanRemote {
// }
// }
public
static
enum
UserType
{
USER
,
REST
}
@Override
public
boolean
authenticate
(
String
username
,
String
password
)
{
boolean
ret
=
(
tryLogin
(
username
,
password
)
!=
null
);
public
AuthenticationResult
authUsername
(
String
username
,
String
password
)
{
logger
.
info
(
"Trying jaas auth with '{}', '{}'"
,
username
,
password
);
AuthenticationResult
ret
=
new
AuthenticationResult
();
ret
.
setUsertype
(
UserType
.
USER
.
name
());
if
((
username
==
null
||
username
.
isEmpty
())
&&
password
.
startsWith
(
"rest:"
))
{
logger
.
info
(
"Trying to jaas auth rest call"
);
ret
.
setUsertype
(
UserType
.
REST
.
name
());
ret
.
setUsername
(
restAuth
(
password
));
}
else
{
EventUser
retUser
=
tryLogin
(
username
,
password
);
if
(
retUser
!=
null
)
{
ret
.
setUsername
(
retUser
.
getLogin
());
}
}
return
ret
;
}
@Override
public
Enumeration
<
String
>
getGroupNames
(
String
user
)
{
public
boolean
authenticate
(
String
username
,
String
password
)
{
return
(
tryLogin
(
username
,
password
)
!=
null
);
}
private
String
restAuth
(
String
restauth
)
{
String
[]
authsplit
=
restauth
.
split
(
":"
);
logger
.
info
(
"Auth split len {}, {}"
,
authsplit
.
length
,
authsplit
);
if
(
authsplit
.
length
!=
6
||
!
authsplit
[
0
].
equals
(
"rest"
))
{
return
null
;
}
return
authenticateApp
(
authsplit
[
1
],
authsplit
[
2
],
authsplit
[
3
],
authsplit
[
4
],
authsplit
[
5
]);
}
@Override
public
Enumeration
<
String
>
getGroupNames
(
String
user
,
String
usertype
)
{
logger
.
info
(
"Fetching groupNames for user {} event {}"
,
user
,
eventbean
.
getCurrentEvent
().
getName
());
EventUser
usr
=
eventUserFacade
.
findByLogin
(
user
.
toLowerCase
().
trim
());
HashSet
<
String
>
roleset
=
new
HashSet
<
String
>();
...
...
@@ -119,6 +166,23 @@ public class JaasBean implements MoyaRealmBeanRemote {
roleset
.
add
(
SpecialPermission
.
ANONYMOUS
.
name
());
}
if
(
usertype
!=
null
)
{
try
{
switch
(
UserType
.
valueOf
(
usertype
))
{
case
REST:
roleset
.
add
(
SpecialPermission
.
REST
.
name
());
break
;
case
USER:
break
;
default
:
throw
new
RuntimeException
(
"Unknown user type: "
+
usertype
);
}
}
catch
(
Throwable
t
)
{
logger
.
warn
(
"UserType authentication "
+
usertype
);
}
}
if
(!
usr
.
getUser
().
isAnonymous
())
{
// all logged in users should be able to logout :)
roleset
.
add
(
UserPermission
.
LOGOUT
.
name
());
...
...
@@ -156,4 +220,44 @@ public class JaasBean implements MoyaRealmBeanRemote {
return
retvect
.
elements
();
}
@Override
public
Enumeration
<
String
>
getGroupNames
(
String
username
)
{
return
getGroupNames
(
username
,
null
);
}
public
String
authenticateApp
(
String
pathInfo
,
String
appId
,
String
userId
,
String
appStamp
,
String
mac
)
{
logger
.
info
(
"pathInfo {}, appid {}, userId {}, appStamp {}, mac {}"
,
pathInfo
,
appId
,
userId
,
appStamp
,
mac
);
if
(
mac
==
null
)
return
null
;
ApiApplication
app
=
appfacade
.
findByAppid
(
appId
);
if
(
app
==
null
)
return
null
;
ApiApplicationInstance
apiInstance
=
appInstanceFacade
.
findInstance
(
app
,
userId
);
if
(
apiInstance
==
null
)
return
null
;
if
(!
app
.
isEnabled
()
||
!
apiInstance
.
isEnabled
())
return
null
;
String
ret
=
null
;
String
macSource
=
PasswordFunctions
.
mkSeparatedString
(
"+"
,
pathInfo
,
appId
,
userId
,
appStamp
,
apiInstance
.
getSecretKey
());
String
macHash
=
PasswordFunctions
.
calculateSha1
(
macSource
);
logger
.
info
(
"Calculated mac hash {} from mac source {}. Sould match {}"
,
macHash
,
macSource
,
mac
);
if
(
mac
.
equalsIgnoreCase
(
macHash
))
{
switch
(
app
.
getAuthtype
())
{
case
ORGAUTH:
ret
=
User
.
ANONYMOUS_LOGINNAME
;
break
;
case
USERKEY:
if
(
apiInstance
.
getEventuser
()
!=
null
)
{
ret
=
apiInstance
.
getEventuser
().
getUser
().
getLogin
();
}
break
;
default
:
throw
new
RuntimeException
(
"Unknown application authtype!"
);
}
}
return
ret
;
}
}
code/MoyaBeans/ejbModule/fi/codecrew/moya/beans/RestBean.java
0 → 100644
View file @
5fe73e1
package
fi
.
codecrew
.
moya
.
beans
;
import
java.util.Collections
;
import
java.util.HashMap
;
import
java.util.Map
;
import
java.util.Map.Entry
;
import
java.util.Random
;
import
javax.annotation.PostConstruct
;
import
javax.annotation.Resource
;
import
javax.ejb.EJB
;
import
javax.ejb.LocalBean
;
import
javax.ejb.SessionContext
;
import
javax.ejb.Singleton
;
import
javax.ejb.Timeout
;
import
javax.ejb.Timer
;
import
javax.ejb.TimerService
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
fi.codecrew.moya.facade.ApiApplicationFacade
;
import
fi.codecrew.moya.facade.ApiApplicationInstanceFacade
;
import
fi.codecrew.moya.utilities.PasswordFunctions
;
/**
* Session Bean implementation class RestAuthBean
*/
@Singleton
@LocalBean
public
class
RestBean
implements
RestBeanLocal
{
/**
* Default constructor.
*/
public
RestBean
()
{
// TODO Auto-generated constructor stub
}
@Resource
private
TimerService
ts
;
@Resource
private
SessionContext
context
;
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
RestBean
.
class
);
@PostConstruct
public
void
initialize
()
{
ts
.
createTimer
(
60
*
1000
,
60
*
1000
,
null
);
}
@EJB
private
ApiApplicationFacade
appfacade
;
@EJB
private
ApiApplicationInstanceFacade
apiInstanceFacade
;
@Timeout
public
void
timeoutNonces
(
Timer
timer
)
{
int
count
=
0
;
long
now
=
System
.
currentTimeMillis
();
synchronized
(
userRestAuths
)
{
for
(
Map
<
String
,
Long
>
ua
:
userRestAuths
.
values
())
{
for
(
Entry
<
String
,
Long
>
no
:
ua
.
entrySet
())
{
if
(
no
!=
null
&&
now
>
no
.
getValue
())
{
ua
.
remove
(
no
.
getKey
());
++
count
;
}
}
}
}
logger
.
info
(
"Timeouted {} nonces"
,
count
);
}
// Username -> Nonce -> expiration
private
Map
<
String
,
Map
<
String
,
Long
>>
userRestAuths
=
Collections
.
synchronizedMap
(
new
HashMap
<
String
,
Map
<
String
,
Long
>>());
@Override
public
String
getLoggedinUserRestNonce
()
{
String
username
=
context
.
getCallerPrincipal
().
getName
();
if
(
username
==
null
)
{
return
null
;
}
Map
<
String
,
Long
>
userAuthMap
=
userRestAuths
.
get
(
username
);
if
(
userAuthMap
==
null
)
{
synchronized
(
userRestAuths
)
{
if
(!
userRestAuths
.
containsKey
(
username
))
{
userAuthMap
=
Collections
.
synchronizedMap
(
new
HashMap
<
String
,
Long
>());
userRestAuths
.
put
(
username
,
userAuthMap
);
}
}
}
Random
random
=
new
Random
();
int
charcount
=
20
+
random
.
nextInt
(
10
);
String
nonce
=
null
;
do
{
nonce
=
PasswordFunctions
.
generateRandomString
(
charcount
,
PasswordFunctions
.
ALL_CHARS
);
}
while
(
userAuthMap
.
containsKey
(
nonce
));
userAuthMap
.
put
(
nonce
,
System
.
currentTimeMillis
()
+
120
*
1000
);
// Timeout in 60 seconds.
return
nonce
;
}
@Override
public
boolean
validateUserNonce
(
String
nonce
)
{
String
username
=
context
.
getCallerPrincipal
().
getName
();
boolean
ret
=
false
;
// Validation is successfull if user exists, nonce exists and timeout has not passed.
if
(
username
!=
null
&&
userRestAuths
.
containsKey
(
username
))
{
Long
time
=
userRestAuths
.
get
(
username
).
remove
(
nonce
);
ret
=
time
!=
null
&&
time
>
System
.
currentTimeMillis
();
}
return
ret
;
}
}
code/MoyaBeans/ejbModule/fi/codecrew/moya/facade/ApiApplicationFacade.java
0 → 100644
View file @
5fe73e1
package
fi
.
codecrew
.
moya
.
facade
;
import
javax.ejb.LocalBean
;
import
javax.ejb.Stateless
;
import
javax.persistence.criteria.CriteriaBuilder
;
import
javax.persistence.criteria.CriteriaQuery
;
import
javax.persistence.criteria.Root
;
import
fi.codecrew.moya.model.ApiApplication
;
import
fi.codecrew.moya.model.ApiApplication_
;
@Stateless
@LocalBean
public
class
ApiApplicationFacade
extends
IntegerPkGenericFacade
<
ApiApplication
>
{
public
ApiApplicationFacade
()
{
super
(
ApiApplication
.
class
);
}
public
ApiApplication
findByAppid
(
String
appId
)
{
CriteriaBuilder
cb
=
getEm
().
getCriteriaBuilder
();
CriteriaQuery
<
ApiApplication
>
q
=
cb
.
createQuery
(
ApiApplication
.
class
);
Root
<
ApiApplication
>
root
=
q
.
from
(
ApiApplication
.
class
);
q
.
where
(
cb
.
equal
(
root
.
get
(
ApiApplication_
.
applicationKey
),
appId
));
return
super
.
getSingleNullableResult
(
getEm
().
createQuery
(
q
));
}
}
code/MoyaBeans/ejbModule/fi/codecrew/moya/facade/ApiApplicationInstanceFacade.java
0 → 100644
View file @
5fe73e1
package
fi
.
codecrew
.
moya
.
facade
;
import
javax.ejb.LocalBean
;
import
javax.ejb.Stateless
;
import
javax.persistence.criteria.CriteriaBuilder
;
import
javax.persistence.criteria.CriteriaQuery
;
import
javax.persistence.criteria.Root
;
import
fi.codecrew.moya.model.ApiApplication
;
import
fi.codecrew.moya.model.ApiApplicationInstance
;
import
fi.codecrew.moya.model.ApiApplicationInstance_
;
@Stateless
@LocalBean
public
class
ApiApplicationInstanceFacade
extends
IntegerPkGenericFacade
<
ApiApplicationInstance
>
{
public
ApiApplicationInstanceFacade
()
{
super
(
ApiApplicationInstance
.
class
);
}
public
ApiApplicationInstance
findInstance
(
ApiApplication
app
,
String
userId
)
{
CriteriaBuilder
cb
=
getEm
().
getCriteriaBuilder
();
CriteriaQuery
<
ApiApplicationInstance
>
q
=
cb
.
createQuery
(
ApiApplicationInstance
.
class
);
Root
<
ApiApplicationInstance
>
root
=
q
.
from
(
ApiApplicationInstance
.
class
);
q
.
where
(
cb
.
equal
(
root
.
get
(
ApiApplicationInstance_
.
application
),
app
),
cb
.
equal
(
root
.
get
(
ApiApplicationInstance_
.
authname
),
userId
));
return
super
.
getSingleNullableResult
(
getEm
().
createQuery
(
q
));
}
}
code/MoyaBeansClient/ejbModule/fi/codecrew/moya/beans/RestBeanLocal.java
0 → 100644
View file @
5fe73e1
package
fi
.
codecrew
.
moya
.
beans
;
import
javax.ejb.Local
;
@Local
public
interface
RestBeanLocal
{
boolean
validateUserNonce
(
String
nonce
);
String
getLoggedinUserRestNonce
();
// String authenticateApp(String pathInfo, String appId, String userid, String applicationStamp, String mac);
}
code/MoyaDatabase/src/fi/codecrew/moya/model/ApiApplication.java
0 → 100644
View file @
5fe73e1
package
fi
.
codecrew
.
moya
.
model
;
import
java.util.ArrayList
;
import
java.util.Date
;
import
java.util.List
;
import
javax.persistence.Column
;
import
javax.persistence.Entity
;
import
javax.persistence.EnumType
;
import
javax.persistence.Enumerated
;
import
javax.persistence.JoinColumn
;
import
javax.persistence.Lob
;
import
javax.persistence.ManyToOne
;
import
javax.persistence.OneToMany
;
import
javax.persistence.Table
;
import
javax.persistence.Temporal
;
import
javax.persistence.TemporalType
;
import
org.eclipse.persistence.annotations.OptimisticLocking
;
import
org.eclipse.persistence.annotations.OptimisticLockingType
;
@Entity
@Table
(
name
=
"api_applications"
)
@OptimisticLocking
(
type
=
OptimisticLockingType
.
CHANGED_COLUMNS
)
public
class
ApiApplication
extends
GenericEntity
{
public
static
enum
AuthType
{
USERKEY
,
ORGAUTH
}
/**
*
*/
private
static
final
long
serialVersionUID
=
-
2283975589693287217L
;
@JoinColumn
(
nullable
=
false
,
updatable
=
false
)
@ManyToOne
private
User
developer
;
@Lob
@Column
(
nullable
=
false
,
unique
=
true
)
private
String
applicationKey
;
@Column
(
nullable
=
false
,
unique
=
true
)
private
String
name
;
@Lob
private
String
description
;
@Column
(
nullable
=
false
,
updatable
=
false
)
@Temporal
(
TemporalType
.
TIMESTAMP
)
private
Date
created
;
@Column
(
nullable
=
false
)
@Enumerated
(
EnumType
.
STRING
)
private
AuthType
authtype
=
AuthType
.
USERKEY
;
@Column
(
nullable
=
false
)
private
boolean
enabled
=
true
;
@Enumerated
(
EnumType
.
STRING
)
private
ReaderType
readerType
;
@OneToMany
(
mappedBy
=
"application"
)
private
List
<
ApiApplicationInstance
>
instances
=
new
ArrayList
<>();
public
User
getDeveloper
()
{
return
developer
;
}
public
void
setDeveloper
(
User
developer
)
{
this
.
developer
=
developer
;
}
public
String
getApplicationKey
()
{
return
applicationKey
;
}
public
void
setApplicationKey
(
String
applicationKey
)
{
this
.
applicationKey
=
applicationKey
;
}
public
String
getName
()
{
return
name
;
}
public
void
setName
(
String
name
)
{
this
.
name
=
name
;
}
public
String
getDescription
()
{
return
description
;
}
public
void
setDescription
(
String
description
)
{
this
.
description
=
description
;
}
public
Date
getCreated
()
{
return
created
;
}
public
void
setCreated
(
Date
created
)
{
this
.
created
=
created
;
}
public
AuthType
getAuthtype
()
{
return
authtype
;
}
public
void
setAuthtype
(
AuthType
authtype
)
{
this
.
authtype
=
authtype
;
}
public
boolean
isEnabled
()
{
return
enabled
;
}
public
void
setEnabled
(
boolean
enabled
)
{
this
.
enabled
=
enabled
;
}
public
ReaderType
getReaderType
()
{
return
readerType
;
}
public
void
setReaderType
(
ReaderType
readerType
)
{
this
.
readerType
=
readerType
;
}
public
List
<
ApiApplicationInstance
>
getInstances
()
{
return
instances
;
}
public
void
setInstances
(
List
<
ApiApplicationInstance
>
instances
)
{
this
.
instances
=
instances
;
}
}
code/MoyaDatabase/src/fi/codecrew/moya/model/ApiApplicationInstance.java
0 → 100644
View file @
5fe73e1
package
fi
.
codecrew
.
moya
.
model
;
import
java.util.Date
;
import
java.util.List
;
import
javax.persistence.Column
;
import
javax.persistence.Entity
;
import
javax.persistence.JoinColumn
;
import
javax.persistence.Lob
;
import
javax.persistence.ManyToOne
;
import
javax.persistence.OneToMany
;
import
javax.persistence.Table
;
import
javax.persistence.Temporal
;
import
javax.persistence.TemporalType
;
import
javax.persistence.UniqueConstraint
;
@Entity
@Table
(
name
=
"api_application_instances"
,
uniqueConstraints
=
@UniqueConstraint
(
columnNames
=
{
ApiApplicationInstance
.
APPLICATION_ID_COLUMN
,
ApiApplicationInstance
.
AUTHNAME_COLUMN
}))
public
class
ApiApplicationInstance
extends
GenericEntity
{
public
static
final
String
UNIQUE_KEY_COLUMN
=
"secret_key"
;
public
static
final
String
APPLICATION_ID_COLUMN
=
"application_id"
;
private
static
final
long
serialVersionUID
=
8311790714131060263L
;
public
static
final
String
AUTHNAME_COLUMN
=
"authname"
;
@JoinColumn
(
nullable
=
false
,
name
=
APPLICATION_ID_COLUMN
,
updatable
=
false
)
@ManyToOne
()
private
ApiApplication
application
;
@Column
(
nullable
=
false
)
private
boolean
enabled
=
true
;
@Column
(
nullable
=
false
,
updatable
=
false
)
@Temporal
(
TemporalType
.
TIMESTAMP
)
private
Date
created
;
@Column
(
nullable
=
false
,
updatable
=
false
,
name
=
AUTHNAME_COLUMN
)
private
String
authname
;
@Lob
private
String
name
;
@OneToMany
()
private
List
<
Reader
>
readers
;
@Lob
private
String
notes
;
@JoinColumn
(
nullable
=
true
)
@ManyToOne
private
EventUser
eventuser
;
@Lob
@Column
(
name
=
UNIQUE_KEY_COLUMN
,
nullable
=
false
,
updatable
=
false
)
private
String
secretKey
;
public
ApiApplication
getApplication
()
{
return
application
;
}
public
void
setApplication
(
ApiApplication
application
)
{
this
.
application
=
application
;
}
public
boolean
isEnabled
()
{
return
enabled
;
}
public
void
setEnabled
(
boolean
enabled
)
{
this
.
enabled
=
enabled
;
}
public
Date
getCreated
()
{
return
created
;
}
public
void
setCreated
(
Date
created
)
{
this
.
created
=
created
;
}
public
String
getName
()
{
return
name
;
}
public
void
setName
(
String
name
)
{
this
.
name
=
name
;
}
public
List
<
Reader
>
getReaders
()
{
return
readers
;
}
public
void
setReaders
(
List
<
Reader
>
readers
)
{
this
.
readers
=
readers
;
}
public
String
getNotes
()
{
return
notes
;
}
public
void
setNotes
(
String
notes
)
{
this
.
notes
=
notes
;
}
public
EventUser
getEventuser
()
{
return
eventuser
;
}
public
void
setEventuser
(
EventUser
eventuser
)
{
this
.
eventuser
=
eventuser
;
}
public
String
getAuthname
()
{
return
authname
;
}
public
void
setAuthname
(
String
authname
)
{
this
.
authname
=
authname
;
}
public
String
getSecretKey
()
{
return
secretKey
;
}
public
void
setSecretKey
(
String
secretKey
)
{
this
.
secretKey
=
secretKey
;
}
}
code/MoyaUtilities/src/main/java/fi/codecrew/moya/enums/apps/SpecialPermission.java
View file @
5fe73e1
...
...
@@ -5,7 +5,8 @@ public enum SpecialPermission {
USER
,
ANONYMOUS
,
// ORGANISATION_ADMIN,
VERKKOMAKSU_CHECKER
VERKKOMAKSU_CHECKER
,
REST
;
public
static
final
String
S_USER
=
"USER"
;
...
...
code/MoyaWeb/src/fi/codecrew/moya/HostnameFilter.java
View file @
5fe73e1
package
fi
.
codecrew
.
moya
;
import
java.io.IOException
;
import
java.io.PrintWriter
;
import
javax.ejb.EJB
;
import
javax.faces.application.ProjectStage
;
...
...
@@ -12,13 +13,16 @@ import javax.servlet.ServletException;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletResponse
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
fi.codecrew.moya.beans.RestBeanLocal
;
import
fi.codecrew.moya.beans.SessionMgmtBeanLocal
;
import
fi.codecrew.moya.clientutils.BortalLocalContextHolder
;
import
fi.codecrew.moya.model.User
;
import
fi.codecrew.moya.rest.RestApplicationEntrypoint
;
/**
* Servlet Filter implementation class HostnameFilter
...
...
@@ -26,8 +30,22 @@ import fi.codecrew.moya.model.User;
public
class
HostnameFilter
implements
Filter
{
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
HostnameFilter
.
class
);
private
boolean
developmentMode
=
false
;
private
static
final
String
HTTP_HOSTNAME_ID
=
"moya_hostname_session_id"
;
private
boolean
developmentMode
=
false
;
@EJB
private
RestBeanLocal
restauth
;
@Override
public
void
init
(
FilterConfig
config
)
throws
ServletException
{
// check if software is in development -mode
FacesContext
fc
=
FacesContext
.
getCurrentInstance
();
if
(
ProjectStage
.
Development
.
equals
(
fc
.
getApplication
().
getProjectStage
()))
{
developmentMode
=
true
;
}
}
@EJB
private
SessionMgmtBeanLocal
sessionmgmt
;
...
...
@@ -51,68 +69,33 @@ public class HostnameFilter implements Filter {
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
@SuppressWarnings
(
"unchecked"
)
@Override
public
void
doFilter
(
ServletRequest
request
,
ServletResponse
response
,
FilterChain
chain
)
throws
IOException
,
ServletException
{
logger
.
info
(
"HostnameFilter called!"
);
HttpServletRequest
httpRequest
=
null
;
if
(
request
!=
null
&&
request
instanceof
HttpServletRequest
)
{
httpRequest
=
((
HttpServletRequest
)
request
);
StringBuffer
url
=
httpRequest
.
getRequestURL
();
// logger.info("Original hostname {}", url);
// Subject subj = Subject.getSubject(AccessController.getContext());
// int beginindex = 8; // Let's skip http://
int
beginindex
=
url
.
indexOf
(
"//"
,
0
);
if
(
beginindex
<
0
)
{
beginindex
=
0
;
}
else
{
beginindex
=
beginindex
+
2
;
}
// Find the first / from URL after http://
int
slashindex
=
url
.
indexOf
(
"/"
,
beginindex
);
int
colonindex
=
url
.
indexOf
(
":"
,
beginindex
);
int
lastindex
=
slashindex
;
if
(
colonindex
>=
0
&&
slashindex
>
colonindex
)
{
lastindex
=
colonindex
;
}
if
(
lastindex
<
0
)
{
lastindex
=
url
.
length
()
-
1
;
}
String
hostname
=
url
.
substring
(
beginindex
,
lastindex
);
// httpRequest.getSession().setAttribute(EventBeanLocal.HTTP_URL_HOSTNAME,
// hostname);
String
proto
=
url
.
substring
(
0
,
5
).
toLowerCase
();
boolean
ssl
=
proto
.
equals
(
"https"
);
BortalLocalContextHolder
.
setSsl
(
ssl
);
BortalLocalContextHolder
.
setHostname
(
hostname
);
BortalLocalContextHolder
.
setInDevelopmentMode
(
developmentMode
);
//
// Object hostname_session_id =
// httpRequest.getSession().getAttribute(HTTP_HOSTNAME_ID);
// if (hostname_session_id != null && hostname_session_id instanceof
// Integer) {
// BortalLocalContextHolder.setHostnameId((Integer)
// hostname_session_id);
// } else {
// BortalLocalContextHolder.setHostnameId(null);
// }
parseHostname
(
httpRequest
);
if
(
httpRequest
.
getUserPrincipal
()
==
null
)
{
try
{
httpRequest
.
login
(
User
.
ANONYMOUS_LOGINNAME
,
null
);
}
catch
(
Throwable
t
)
{
logger
.
warn
(
"Error logging in as anonymous... ignoring.. "
,
t
);
// Check if we are logging in with rest
if
(
RestApplicationEntrypoint
.
REST_PATH
.
equals
(
httpRequest
.
getServletPath
()))
{
if
(!
restAuth
(
httpRequest
,
response
))
{
response
.
getWriter
().
write
(
"REST authentication failed!"
);
if
(
response
instanceof
HttpServletResponse
)
{
HttpServletResponse
httpResp
=
(
HttpServletResponse
)
response
;
httpResp
.
setStatus
(
HttpServletResponse
.
SC_FORBIDDEN
);
}
return
;
}
}
else
{
try
{
httpRequest
.
login
(
User
.
ANONYMOUS_LOGINNAME
,
null
);
}
catch
(
Throwable
t
)
{
logger
.
warn
(
"Error logging in as anonymous... ignoring.. "
,
t
);
}
}
}
else
if
(!
httpRequest
.
getUserPrincipal
().
getName
().
equals
(
User
.
ANONYMOUS_LOGINNAME
))
...
...
@@ -120,24 +103,6 @@ public class HostnameFilter implements Filter {
sessionmgmt
.
updateSessionUser
(
httpRequest
.
getSession
().
getId
(),
httpRequest
.
getUserPrincipal
().
getName
());
}
// Object trailO =
// httpRequest.getSession().getAttribute(HTTP_TRAIL_NAME);
// ConcurrentLinkedQueue<Object> trail = null;
// if (trailO != null && trailO instanceof ConcurrentLinkedQueue)
// {
// trail = (ConcurrentLinkedQueue<Object>) trailO;
// } else {
// trail = new ConcurrentLinkedQueue<Object>();
// httpRequest.getSession().setAttribute(HTTP_TRAIL_NAME, trail);
// }
// for (int remove = trail.size() - 10; remove > 0; --remove) {
// Object removed = trail.poll();
// logger.debug("Removed {} from http trail", removed);
// }
// if (!httpRequest.getRequestURI().matches(".*(resource).*")) {
// trail.add(httpRequest.getRequestURI());
// }
}
// pass the request along the filter chain
try
{
...
...
@@ -147,19 +112,6 @@ public class HostnameFilter implements Filter {
}
}
/**
* @see Filter#init(FilterConfig)
*/
@Override
public
void
init
(
FilterConfig
fConfig
)
throws
ServletException
{
// check if software is in development -mode
FacesContext
fc
=
FacesContext
.
getCurrentInstance
();
if
(
ProjectStage
.
Development
.
equals
(
fc
.
getApplication
().
getProjectStage
()))
{
developmentMode
=
true
;
}
}
// public static String getCurrentHostname(HttpSession sess) {
// String ret = null;
// if (sess != null) {
...
...
@@ -171,4 +123,89 @@ public class HostnameFilter implements Filter {
// return ret;
// }
private
boolean
restAuth
(
HttpServletRequest
httpRequest
,
ServletResponse
response
)
{
StringBuilder
hashBuilder
=
new
StringBuilder
();
hashBuilder
.
append
(
"rest:"
);
hashBuilder
.
append
(
httpRequest
.
getPathInfo
()).
append
(
":"
);
hashBuilder
.
append
(
httpRequest
.
getParameter
(
"appkey"
)).
append
(
":"
);
hashBuilder
.
append
(
httpRequest
.
getParameter
(
"appuser"
)).
append
(
":"
);
hashBuilder
.
append
(
httpRequest
.
getParameter
(
"appstamp"
)).
append
(
":"
);
hashBuilder
.
append
(
httpRequest
.
getParameter
(
"appmac"
));
boolean
ret
=
true
;
try
{
httpRequest
.
login
(
null
,
hashBuilder
.
toString
());
}
catch
(
ServletException
loginEx
)
{
ret
=
false
;
logger
.
info
(
"Rest api authentication failed! "
,
loginEx
);
if
(
response
instanceof
HttpServletResponse
)
{
HttpServletResponse
httpResp
=
((
HttpServletResponse
)
response
);
httpResp
.
setStatus
(
HttpServletResponse
.
SC_FORBIDDEN
);
try
{
PrintWriter
w
=
httpResp
.
getWriter
();
w
.
write
(
"Rest auth failed! "
);
w
.
flush
();
}
catch
(
IOException
e
)
{
logger
.
info
(
"Error writing error message from restauth failure to ostream"
,
e
);
}
}
}
finally
{
}
return
ret
;
}
protected
void
parseHostname
(
HttpServletRequest
httpRequest
)
{
logger
.
info
(
"Path info {}"
,
httpRequest
.
getPathInfo
());
logger
.
info
(
"querystring {}"
,
httpRequest
.
getQueryString
());
logger
.
info
(
"ctxpath {}"
,
httpRequest
.
getContextPath
());
logger
.
info
(
"pathTranslated {}"
,
httpRequest
.
getPathTranslated
());
logger
.
info
(
"requestUri {}"
,
httpRequest
.
getRequestURI
());
logger
.
info
(
"URL {}"
,
httpRequest
.
getRequestURL
().
toString
());
logger
.
info
(
"servletpath {}"
,
httpRequest
.
getServletPath
());
logger
.
info
(
"servletCtx {}"
,
httpRequest
.
getServletContext
());
StringBuffer
url
=
httpRequest
.
getRequestURL
();
// logger.info("Original hostname {}", url);
// Subject subj = Subject.getSubject(AccessController.getContext());
// int beginindex = 8; // Let's skip http://
int
beginindex
=
url
.
indexOf
(
"//"
,
0
);
if
(
beginindex
<
0
)
{
beginindex
=
0
;
}
else
{
beginindex
=
beginindex
+
2
;
}
// Find the first / from URL after http://
int
slashindex
=
url
.
indexOf
(
"/"
,
beginindex
);
int
colonindex
=
url
.
indexOf
(
":"
,
beginindex
);
int
lastindex
=
slashindex
;
if
(
colonindex
>=
0
&&
slashindex
>
colonindex
)
{
lastindex
=
colonindex
;
}
if
(
lastindex
<
0
)
{
lastindex
=
url
.
length
()
-
1
;
}
String
hostname
=
url
.
substring
(
beginindex
,
lastindex
);
// httpRequest.getSession().setAttribute(EventBeanLocal.HTTP_URL_HOSTNAME,
// hostname);
String
proto
=
url
.
substring
(
0
,
5
).
toLowerCase
();
boolean
ssl
=
proto
.
equals
(
"https"
);
BortalLocalContextHolder
.
setSsl
(
ssl
);
BortalLocalContextHolder
.
setHostname
(
hostname
);
BortalLocalContextHolder
.
setInDevelopmentMode
(
developmentMode
);
}
}
code/MoyaWeb/src/fi/codecrew/moya/rest/ApplicationRestView.java
0 → 100644
View file @
5fe73e1
package
fi
.
codecrew
.
moya
.
rest
;
import
javax.enterprise.context.RequestScoped
;
import
javax.ws.rs.Consumes
;
import
javax.ws.rs.Path
;
import
javax.ws.rs.Produces
;
import
javax.ws.rs.core.MediaType
;
import
javax.ws.rs.core.Response
;
import
javax.ws.rs.core.Response.Status
;
@RequestScoped
@Path
(
"/app"
)
@Consumes
({
MediaType
.
APPLICATION_JSON
,
MediaType
.
APPLICATION_XML
})
@Produces
({
MediaType
.
APPLICATION_JSON
+
"; charset=UTF-8"
})
public
class
ApplicationRestView
{
@Path
(
"/hello"
)
public
Response
hello
()
{
return
Response
.
ok
().
status
(
Status
.
FORBIDDEN
).
build
();
}
}
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment