Write Metrics in case of New Style Endpoints - added Consumer data

This commit is contained in:
constantine2nd 2018-01-15 22:05:24 +01:00
parent b0995e66f6
commit a0465aeabf
6 changed files with 88 additions and 40 deletions

View File

@ -193,9 +193,10 @@ trait OBPRestHelper extends RestHelper with MdcLoggable {
def failIfBadAuthorizationHeader(rd: Option[ResourceDoc])(fn: SessionContext => Box[JsonResponse]) : JsonResponse = {
val sc = SessionContext(resourceDocument = rd, startTime = Some(Helpers.now))
val authorization = S.request.map(_.header("Authorization")).flatten
if(newStyleEndpoints(rd)) {
fn(sc)
} else if (hasAnOAuthHeader) {
} else if (hasAnOAuthHeader(authorization)) {
val usr = getUser
usr match {
case Full(u) => fn(sc.copy(user = Full(u))) // Authentication is successful
@ -203,7 +204,7 @@ trait OBPRestHelper extends RestHelper with MdcLoggable {
case Failure(msg, t, c) => Failure(msg, t, c)
case _ => Failure("oauth error")
}
} else if (Props.getBool("allow_direct_login", true) && hasDirectLoginHeader) {
} else if (Props.getBool("allow_direct_login", true) && hasDirectLoginHeader(authorization)) {
DirectLogin.getUser match {
case Full(u) => fn(sc.copy(user = Full(u)))// Authentication is successful
case _ => {
@ -211,7 +212,7 @@ trait OBPRestHelper extends RestHelper with MdcLoggable {
Full(errorJsonResponse(message, httpCode))
}
}
} else if (Props.getBool("allow_gateway_login", false) && hasGatewayHeader) {
} else if (Props.getBool("allow_gateway_login", false) && hasGatewayHeader(authorization)) {
logger.info("allow_gateway_login-getRemoteIpAddress: " + getRemoteIpAddress() )
Props.get("gateway.host") match {
case Full(h) if h.split(",").toList.exists(_.equalsIgnoreCase(getRemoteIpAddress()) == true) => // Only addresses from white list can use this feature

View File

@ -475,7 +475,7 @@ object DirectLogin extends RestHelper with MdcLoggable {
_ <- Future { if (httpCode == 400 || httpCode == 401) Empty else Full("ok") } map { x => fullBoxOrException(x ?~! message) }
user <- OAuthHandshake.getUserFromTokenFuture(200, (if (directLoginParameters.isDefinedAt("token")) directLoginParameters.get("token") else Empty))
} yield {
(user, Some(sc.copy(user = user)))
(user, Some(sc.copy(user = user, directLoginParams = directLoginParameters)))
}
}
@ -532,4 +532,15 @@ object DirectLogin extends RestHelper with MdcLoggable {
}
consumer
}
def getConsumer(sc: SessionContext): Box[Consumer] = {
val consumer: Option[Consumer] = for {
tokenId: String <- sc.directLoginParams.get("token")
token: Token <- Tokens.tokens.vend.getTokenByKey(tokenId)
consumer: Consumer <- token.consumer
} yield {
consumer
}
consumer
}
}

View File

@ -891,6 +891,18 @@ object OAuthHandshake extends RestHelper with MdcLoggable {
consumer
}
def getConsumer(sc: SessionContext): Box[Consumer] = {
import code.model.Token
val consumer: Option[Consumer] = for {
tokenId: String <- sc.oAuthParams.get("oauth_token")
token: Token <- Tokens.tokens.vend.getTokenByKey(tokenId)
consumer: Consumer <- token.consumer
} yield {
consumer
}
consumer
}
def getUser : Box[User] = {
val httpMethod = S.request match {
@ -937,7 +949,7 @@ object OAuthHandshake extends RestHelper with MdcLoggable {
_ <- Future { if (httpCode == 200) Full("ok") else Empty } map { x => APIUtil.fullBoxOrException(x ?~! message) }
user <- getUserFromTokenFuture(httpCode, oAuthParameters.get("oauth_token"))
} yield {
(user, Some(sc.copy(user = user)))
(user, Some(sc.copy(user = user, oAuthParams = oAuthParameters)))
}
}
def getUserFromTokenFuture(httpCode : Int, key: Box[String]) : Future[Box[User]] = {

View File

@ -390,18 +390,15 @@ object APIUtil extends MdcLoggable {
case _ => "GET"
}
def hasDirectLoginHeader : Boolean = hasHeader("DirectLogin")
def hasDirectLoginHeader(authorization: Box[String]): Boolean = hasHeader("DirectLogin", authorization)
def hasAnOAuthHeader : Boolean = hasHeader("OAuth")
def hasAnOAuthHeader(authorization: Box[String]): Boolean = hasHeader("OAuth", authorization)
def hasGatewayHeader() = hasHeader("GatewayLogin")
def hasGatewayHeader(authorization: Box[String]) = hasHeader("GatewayLogin", authorization)
def hasHeader(`type`: String) : Boolean = {
S.request match {
case Full(a) => a.header("Authorization") match {
case Full(parameters) => parameters.contains(`type`)
case _ => false
}
def hasHeader(`type`: String, authorization: Box[String]) : Boolean = {
authorization match {
case Full(a) if a.contains(`type`) => true
case _ => false
}
}
@ -439,17 +436,37 @@ object APIUtil extends MdcLoggable {
case _ => -1
}
//execute saveMetric in future, as we do not need to know result of operation
//execute saveMetric in future, as we do not need to know result of the operation
Future {
val consumer =
if (hasAnOAuthHeader(sc.authorization)) {
getConsumer(sc) match {
case Full(c) => Full(c)
case _ => Empty
}
} else if (Props.getBool("allow_direct_login", true) && hasDirectLoginHeader(sc.authorization)) {
DirectLogin.getConsumer(sc) match {
case Full(c) => Full(c)
case _ => Empty
}
} else {
Empty
}
val c: Consumer = consumer.orNull
//The consumerId, not key
val consumerId = if (u != null) c.id.toString() else "null"
val appName = if (u != null) c.name.toString() else "null"
val developerEmail = if (u != null) c.developerEmail.toString() else "null"
APIMetrics.apiMetrics.vend.saveMetric(
userId,
sc.url,
sc.startTime.getOrElse(null),
duration,
userName,
"appName",
"developerEmail",
"consumerId",
appName,
developerEmail,
consumerId,
implementedByPartialFunction,
sc.implementedInVersion,
sc.verb,
@ -463,14 +480,15 @@ object APIUtil extends MdcLoggable {
}
def logAPICall(date: TimeSpan, duration: Long, rd: Option[ResourceDoc]) = {
val authorization = S.request.map(_.header("Authorization")).flatten
if(Props.getBool("write_metrics", false)) {
val user =
if (hasAnOAuthHeader) {
if (hasAnOAuthHeader(authorization)) {
getUser match {
case Full(u) => Full(u)
case _ => Empty
}
} else if (Props.getBool("allow_direct_login", true) && hasDirectLoginHeader) {
} else if (Props.getBool("allow_direct_login", true) && hasDirectLoginHeader(authorization)) {
DirectLogin.getUser match {
case Full(u) => Full(u)
case _ => Empty
@ -480,12 +498,12 @@ object APIUtil extends MdcLoggable {
}
val consumer =
if (hasAnOAuthHeader) {
if (hasAnOAuthHeader(authorization)) {
getConsumer match {
case Full(c) => Full(c)
case _ => Empty
}
} else if (Props.getBool("allow_direct_login", true) && hasDirectLoginHeader) {
} else if (Props.getBool("allow_direct_login", true) && hasDirectLoginHeader(authorization)) {
DirectLogin.getConsumer match {
case Full(c) => Full(c)
case _ => Empty
@ -1875,17 +1893,18 @@ Versions are groups of endpoints in a file
*/
def getUserAndSessionContextFuture(sc: SessionContext): Future[(Box[User], Option[SessionContext])] = {
val s = S
val authorization = S.request.map(_.header("Authorization")).flatten
val spelling = getSpellingParam()
val implementedInVersion = S.request.openOrThrowException("Attempted to open an empty Box.").view
val verb = S.request.openOrThrowException("Attempted to open an empty Box.").requestType.method
val url = S.uriAndQueryString.getOrElse("")
val correlationId = getCorrelationId()
val res =
if (hasAnOAuthHeader) {
if (hasAnOAuthHeader(authorization)) {
getUserFromOAuthHeaderFuture(sc)
} else if (Props.getBool("allow_direct_login", true) && hasDirectLoginHeader) {
} else if (Props.getBool("allow_direct_login", true) && hasDirectLoginHeader(authorization)) {
DirectLogin.getUserFromDirectLoginHeaderFuture(sc)
} else if (Props.getBool("allow_gateway_login", false) && hasGatewayHeader) {
} else if (Props.getBool("allow_gateway_login", false) && hasGatewayHeader(authorization)) {
Props.get("gateway.host") match {
case Full(h) if h.split(",").toList.exists(_.equalsIgnoreCase(getRemoteIpAddress()) == true) => // Only addresses from white list can use this feature
val (httpCode, message, parameters) = GatewayLogin.validator(s.request)
@ -1938,6 +1957,8 @@ Versions are groups of endpoints in a file
x => (x._1, x._2.map(_.copy(url = url)))
} map {
x => (x._1, x._2.map(_.copy(correlationId = correlationId)))
} map {
x => (x._1, x._2.map(_.copy(authorization = authorization)))
}
}

View File

@ -8,18 +8,20 @@ import code.model.User
import net.liftweb.common.{Box, Empty}
import net.liftweb.json.JsonAST.JValue
case class SessionContext(
gatewayLoginRequestPayload: Option[PayloadOfJwtJSON] = None,
gatewayLoginResponseHeader: Option[String] = None,
spelling: Option[String] = None,
user: Box[User] = Empty,
resourceDocument: Option[ResourceDoc] = None,
startTime: Option[Date] = None,
endTime: Option[Date] = None,
correlationId: String = "",
url: String = "",
verb: String = "",
implementedInVersion: String = ""
case class SessionContext(gatewayLoginRequestPayload: Option[PayloadOfJwtJSON] = None,
gatewayLoginResponseHeader: Option[String] = None,
spelling: Option[String] = None,
user: Box[User] = Empty,
resourceDocument: Option[ResourceDoc] = None,
startTime: Option[Date] = None,
endTime: Option[Date] = None,
correlationId: String = "",
url: String = "",
verb: String = "",
implementedInVersion: String = "",
authorization: Box[String] = Empty,
directLoginParams: Map[String, String] = Map(),
oAuthParams: Map[String, String] = Map()
)
trait GatewayLoginParam
case class GatewayLoginRequestPayload(jwtPayload: Option[PayloadOfJwtJSON]) extends GatewayLoginParam

View File

@ -289,15 +289,16 @@ import net.liftweb.util.Helpers._
*
*/
def getCurrentUser: Box[User] = {
val authorization = S.request.map(_.header("Authorization")).flatten
for {
resourceUser <- if (AuthUser.currentUser.isDefined)
//AuthUser.currentUser.get.user.foreign // this will be issue when the resource user is in remote side
Users.users.vend.getUserByUserName(AuthUser.currentUser.openOrThrowException("Attempted to open an empty Box.").username.get)
else if (hasDirectLoginHeader)
else if (hasDirectLoginHeader(authorization))
DirectLogin.getUser
else if (hasAnOAuthHeader) {
else if (hasAnOAuthHeader(authorization)) {
OAuthHandshake.getUser
} else if (hasGatewayHeader()){
} else if (hasGatewayHeader(authorization)){
GatewayLogin.getUser
} else {
debug(ErrorMessages.CurrentUserNotFoundException)