Created
August 19, 2016 01:55
-
-
Save nallwhy/d0bde64df0fe82dc60bbd112d2264399 to your computer and use it in GitHub Desktop.
Rails - Facebook auth
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
def facebook | |
render_api 400, "Missing fields" and return unless check_params(facebook_params, [:id, :access_token]) | |
begin | |
facebook_user = FbGraph2::User.me(params[:access_token]).fetch(fields: [:name, :email, :gender, :birthday, "picture.height(300)"]) | |
user = User.find_by_email(facebook_user.email) | |
if user.nil? | |
# crate | |
meta = { | |
name: facebook_user.name, | |
gender: facebook_user.gender, | |
} | |
unless facebook_user.picture.is_silhouette | |
meta[:facebook_picture] = facebook_user.picture.url | |
end | |
birthday = facebook_user.birthday rescue nil | |
if birthday | |
# TODO: check it works | |
# birthday format is MM/dd/yyyy. change it to yyyy/MM/dd | |
meta[:birthday] = Date.strptime(birthday, '%m/%d/%Y').strftime('%Y/%m/%d') rescue nil | |
end | |
user = User.create(email: facebook_user.email, | |
password: Devise.friendly_token, | |
auth_info: { | |
type: "facebook", | |
info: { | |
id: facebook_params[:id] | |
} | |
}, | |
meta: meta) | |
if user.save | |
sign_in(user) | |
render_api 201, user.as_json({:self => true}) | |
else | |
render_api 400, user.errors.full_messages.as_json | |
end | |
else | |
# authenticate | |
if sign_in(user) | |
if !facebook_user.birthday.nil? && current_user.meta['birthday'].nil? | |
current_user.meta['birthday'] = facebook_user.birthday | |
current_user.save! | |
end | |
render_api 200, current_user.as_json({:self => true}) | |
else | |
render_api 500, "Failed to authenticate" | |
end | |
end | |
rescue FbGraph2::Exception => e | |
puts e | |
render_api 500, "Failed to login with facebook" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment