Created
January 9, 2014 09:40
-
-
Save mcalmels/8331764 to your computer and use it in GitHub Desktop.
CORS JSONP
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
/** | |
* Send back a JSON object {"connected": false} | |
* or {"connected": true, "firstname": "Jean", "lastname": "DUPONT"} | |
* | |
* By default, the JSON object is wrapped in JSONP. | |
* But it can be sent as it if we're asked explicitly for JSON (http://…/login.json) | |
* | |
* See http://jsfiddle.net/HjCc2/6/ for usage. | |
*/ | |
def login = { | |
def user | |
try { | |
SecurityContext.setCurrentContext(SecurityContext.FRONT_OFFICE_CONTEXT) | |
if (session.currentEcitizenId) { | |
SecurityContext.setCurrentEcitizen(session.currentEcitizenId) | |
user = userSearchService.getById(session.currentEcitizenId) | |
} | |
} catch (Exception e) { | |
log.error e.message | |
render status: 500 | |
} | |
def map | |
if (user) | |
map = [connected:true, firstname:user.firstName, lastName:user.lastName] | |
else | |
map = [connected:false] | |
withFormat { | |
js { | |
render text: (params.callback ?: 'callback') + '(' + (map as JSON) + ')', | |
contentType: 'text/javascript', | |
status: 200 | |
} | |
json { | |
// Note: '*' can't be used with credentials. | |
response.setHeader 'Access-Control-Allow-Origin', request.getHeader('Origin') | |
response.setHeader 'Access-Control-Allow-Credentials', 'true' | |
render text: map as JSON, | |
contentType: 'application/json', | |
status: 200 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment