How can I create an admin user on my live heroku app? - ruby-on-rails-3

I tried going into the heroku console and adding a user with User.create(name: "admin", email: "admin#tradespring.net", admin: true). These are all valid columns in my user table and I have no problems creating an admin user locally (thought I do it differently. This is what it gives me.
irb(main):001:0> User.create(name: "admin", email:"admin#tradespring.net", admin: true)
WARNING: Can't mass-assign protected attributes: admin
(57.4ms) BEGIN
User Exists (12.4ms) SELECT 1 FROM "users" WHERE LOWER("users"."email") = LOWER('admin#tradespring.net') LIMIT 1
(30.3ms) ROLLBACK
=> #<User id: nil, name: "admin", email: "admin#tradespring.net", created_at: nil, updated_at: nil, password_digest: nil, remember_token: nil, admin: false>
clearly the admin setting didnt work as it is put as false. Also when I go to my site there is no new user named admin. I am not sure I am even taking the right steps though. What am I doing wrong/not doing?

User.create({name: "admin", email:"admin#tradespring.net", admin: true}, :without_protection => true)
An alternative would be to set the attributes one by one:
u = User.new
u.name = "admin"
u.email = "admin#tradespring.net"
u.admin = true
u.save!

Related

Passing Phoenix.Token to and from browser

I’m trying to use Openmaize for user authentication, and having trouble getting phoenix pass a token when a user logs in. It appears that no token is assigned and passed to the client, and therefore Phoenix.Token.verify fails.
IO.inspect(socket) in UserSocket.connect returns this.
Phoenix.Socket{assigns: %{}, channel: nil, channel_pid: nil,
endpoint: SeatSaver.Endpoint, handler: SeatSaver.UserSocket, id: nil,
joined: false, pubsub_server: SeatSaver.PubSub, ref: nil,
serializer: Phoenix.Transports.WebSocketSerializer, topic: nil,
transport: Phoenix.Transports.WebSocket, transport_name: :websocket,
transport_pid: #PID<0.2098.0>}
I defined set_current_user(user, conn) function in authenticate.ex controller that looks like
defp set_current_user(user, conn) do
token = Phoenix.Token.sign(conn, "user socket", user.id)
conn
|> assign(:current_user, user)
|> assign(:user_token, token)
In the app.html.eex, the following has been added.
<script> window.userToken = “<%= assigns[:user_token] %>” </script>
<script src = “<%= static_path(#conn, “/js/app.js”) %>”></script>
in the app.js,
let socket = new Socket(”/socket”, {
params: {token: window.userToken},
…
})
and finally, user_socket.ex has
def connect(%{"token" => token}, socket) do
case Phoenix.Token.verify(socket, "user socket",
token, max_age: #max_age) do
{:ok, user_id} ->
IO.inspect(user_id)
{:ok, assign(socket, :user_id, user_id)}
{:error, _reason} ->
:error # this errors out because token is nil
end
end
First you need to add secret_key_base in config/config.exs.
secret_key_base: xxxxx

how to extend lifetime of a meteor login token?

I have a meteor app that seems to force a logout after 24 hours.
Our app (in beta) is using a "guest login" process where we create accounts on the fly, so i want to actually have an indefinite token lifetime.
Is there a way to extend the lifetime of these tokens?
Error logging in with token: Error: You've been logged out by the server. Please log in again. [403]
update failed: Access denied
Our guest login looks something like this:
postCreateUser = (username, password) ->
dclib.clog("login", "created", username)
Meteor.loginWithPassword username, password, ->
# FIXME? could this be in onCreateUser server side?
Meteor.call "createPersonalRoomIfNone"
if Meteor.isClient
Meteor.startup ->
unless Meteor.userId()
Meteor.call "getLastUserIndex", (err,index)->
if err
throw err
console.log("creating guest user", index)
username = "Guest #{index}"
password = Random.id()
Accounts.createUser
username: username
email: ""
password: password
role: "guest"
, -> postCreateUser(username, password)
this does it i hope!
# prevent users getting logged out
# http://devdocs.io/meteor/index#accounts_config
Accounts.config ({loginExpirationInDays: null})

Why is this FactoryGirl-created object visible in the test, but not in the view that is being tested?

I'm using RSpec, FactoryGirl, and PhantomJS.
UPDATE:
I have verified that if I create this item in my spec/support/login_macros.rb login_user method, which I call below, the listing object is available in the view.
This seems like a FactoryGirl issue. Why can I create from a factory in that helper method, but can't inside the test itself? Here is the support method:
module LoginMacros
def login_user(admin = false)
myrepo = FactoryGirl.create(:repository, :myname)
plan = FactoryGirl.create(:plan, name: "Test Multi", listing_limit: 5000, repositories_allowed: 5)
user = FactoryGirl.create(:user)
subscription = FactoryGirl.create(:subscription, user: user, plan: plan)
user.add_repository(myrepo)
listing = FactoryGirl.create(:listing, user: user, repository: myrepo)
visit login_path
fill_in 'Email', :with => user.email
fill_in 'Password', :with => user.password
click_button 'Go'
user
end
I have set transactional_fixtures to false in my spec_helper.rb. Here is my spec:
require "spec_helper"
describe "App Integration" do
let!(:user) { login_user }
let!(:myrepo) { user.repositories.where(name: "myrepo" ).first }
it "lets a user add apps to a listing", js: true do
listing = FactoryGirl.create(:listing, user: user, repository: myrepo)
puts listing.inspect
Capybara::Screenshot.screenshot_and_open_image
end
end
Now here is the problem. See that puts line above? It prints out the object.
But in the screenshot, it's as if the object were never created. Like magic!
And yet, both the User and the Repository objects are visible in the view.
Also, I can go to a different view and see that Listing object. Just not on the main page of my application!
Why would that object be visible in one view and not the other? I'm just doing this on the main page:
<h3><%= Listing.count %></h3>
And it is always, always, always zero. Makes zero sense.
It doesn't look like you're ever calling visit inside of your test, so the page would always be blank. You need to call visit root_path # (or whatever path that heading is on) before saving the screenshot.
let! blocks are invoked before it blocks. Since you're viewing the page in a let! block but creating the listing in the it block, the listing isn't created until after you've viewed the page.

omniauth google_oauth2 the profile image is not present in the authhash

This is written in omniauth.rb an initializer.
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2,ID,SECRET,
{
:approval_prompt => '',
:scope => 'http://gdata.youtube.com,https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/userinfo.profile'
}
The returned auth hash does not have IMAGE element in the "info", why?????????
Replaced original info with x in the below HASH
*********************
--- !ruby/hash:OmniAuth::AuthHash
provider: google_oauth2
uid: 'xxxxxxxxxxxxxxxxxxxx'
info: !ruby/hash:OmniAuth::AuthHash::InfoHash
name: xxxx xxx
email: xxxxxxxxxx
first_name: xxxxxx
last_name: xxxxxxx
credentials: !ruby/hash:Hashie::Mash
token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
expires_at: 1365434778
expires: true
extra: !ruby/hash:Hashie::Mash
raw_info: !ruby/hash:Hashie::Mash
id: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
email: xxxxxxxxxx.xxx#gmail.com
verified_email: true
name: xxxx xxxx
given_name: xxx
family_name: xxx
link: https://plus.google.com/xxxxxxxxxxx
gender: male
locale: en
*********************
I want the profile image, what am I doing wrong?
Also tried,
{:scope => 'userinfo.email,userinfo.profile'}
Not working!!
Not sure what that scope is doing, but I've just solved getting google info for myself.
Is that information the actual params sent to rails, or is it the saved user hash?
If it's not the actual params you get on login, you can use:
# sessions_controller.rb
raise env["omniauth.auth"].to_yaml
That'll show you everything that google is sending you.
If it's the user and If you've followed Railscasts like I was doing, then check that you've created a field to save the pics and that you've set the field to save the info from the hash. I did this:
# sessions_controller.rb
def create
user = User.from_omniauth(env["omniauth.auth"])
user.image = env["omniauth.auth"]['info']['image']
user.save
session[:user_id] = user.id
redirect_to root_url, :notice => "Signed in!"
end
If that's not what you're needing, can you be more specific?

OR query matching nil or "" with Mongoid still matches ""?

I'm trying to write a query for an embedded Mongoid::Document which finds any record where the "address" field is neither nil nor "".
Using a combination of the MongoDB documentation, this issue in the Mongoid bug reports, and the Mongoid documentation, I think that something like this should work:
scope :with_address, where("$or" => [{:address => {"$ne" => nil}}, {:address => {"$ne" => ""}}])
When I run this, the selector looks ok:
1.9.2p290 :002 > report.document.records.with_address
=> #<Mongoid::Criteria
selector: {"$or"=>[{:address=>{"$ne"=>nil}}, {:address=>{"$ne"=>""}}]},
options: {},
class: GlobalBoarding::MerchantPrincipal,
embedded: true>
But when I look at the results, they contain an entry with a blank address:
1.9.2p290 :007 > report.document.records.with_address.last
<Record _id: 4f593f245af0501074000122, _type: nil, version: 1, name: "principal contact 3", title: "", dob: nil, address: "", email: "", phone: "", fax: "">
I can't figure out if I'm doing a query wrong, if this is a bug with Mongoid, or if there is some other issue. Does anyone have experience with such a query?
in the end, this is the only way i could find that works to select records where a certain field is not nil and not blank:
scope :with_name, all_of(:name.ne => nil).all_of(:name.ne => "")
I think you're going to chuckle at this.
Neither nil nor "" is the same as saying:
Not nil and not "".
You really mean and, and that can be expressed without $and, using just:
$ne=>nil, $ne=>""
You can do the more succint:
scope :with_name, where(:name.nin => ["", nil])
See MongoDB manual.