-
-
Save ngbinh/d28687abf4e8ac8efec8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApiController { | |
protected def getConfig() { | |
getGrailsApplication().config | |
} | |
protected def jsonData(data = null, otherData = null) { | |
([data: data] + (otherData ?: [:])) as JSON | |
} | |
protected def renderUnacceptable() { | |
response.status = 406 | |
withFormat { | |
json { render jsonData('Unacceptable') } | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.* | |
import org.apache.commons.codec.binary.Hex | |
import javax.crypto.Mac | |
import javax.crypto.spec.SecretKeySpec | |
class CryptUtils { | |
static def validateToken(apiKey, timestamp, token, signature) { | |
def value = timestamp + token | |
def mac = Mac.getInstance("HmacSHA256") | |
mac.init(new SecretKeySpec(apiKey.getBytes('UTF-8'), "HmacSHA256")) | |
def valueDigest = mac.doFinal(value.getBytes('UTF-8')) | |
return signature == Hex.encodeHexString(valueDigest) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ReceiveController extends ApiController { | |
static allowedMethods = [ | |
receive: 'POST' | |
] | |
def receive() { | |
if(!CryptUtils.validateToken( | |
config.mailgun.apiKey, | |
params.int('timestamp').toString(), | |
params.token, | |
params.signature | |
)) { | |
renderUnacceptable() | |
return | |
} | |
// .. do your stuff | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment