Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bio field now part of User; status moved off of DrupalUser #1497

Merged
merged 20 commits into from
Jul 7, 2017
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app/controllers/users_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def create
flash[:warning] = I18n.t('users_controller.account_migrated_create_new_password')
redirect_to "/profile/edit"
else
@user.drupal_user.set_bio(params[:drupal_user][:bio])
@user.update_attribute(:bio, params[:drupal_user][:bio])
@user.add_to_lists(['publiclaboratory'])
flash[:notice] = I18n.t('users_controller.registration_successful').html_safe
flash[:warning] = I18n.t('users_controller.spectralworkbench_or_mapknitter', :url1 => "'#{session[:openid_return_to]}'").html_safe if session[:openid_return_to]
Expand All @@ -45,7 +45,7 @@ def update
if current_user
@user = current_user
@user.attributes = params[:user]
@user.drupal_user.set_bio(params[:drupal_user][:bio])
@user.update_attribute(:bio, params[:drupal_user][:bio])
@user.save({}) do |result|
if result
if session[:openid_return_to] # for openid login, redirects back to openid auth process
Expand Down
20 changes: 4 additions & 16 deletions app/models/drupal_users.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ def user
User.find_by_username name
end

def bio
user.bio
end

def username
name
end
Expand Down Expand Up @@ -118,22 +122,6 @@ def profile_values
drupal_profile_values
end

def set_bio(text)
bio = DrupalProfileValue.find_by_uid(uid, conditions: { fid: 7 })
bio = DrupalProfileValue.new(fid: 7, uid: uid) if bio.nil?
bio.value = text
bio.save!
end

def bio
bio = DrupalProfileValue.find_by_uid(uid, conditions: { fid: 7 })
if bio
bio.value || ''
else
''
end
end

def notes
user.notes
end
Expand Down
6 changes: 1 addition & 5 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def validate(record)

class User < ActiveRecord::Base
self.table_name = 'rusers'
attr_accessible :username, :email, :password, :password_confirmation, :openid_identifier, :key, :photo, :photo_file_name, :location_privacy
attr_accessible :username, :email, :password, :password_confirmation, :openid_identifier, :key, :photo, :photo_file_name, :bio

include SolrToggle
searchable if: :shouldIndexSolr do
Expand Down Expand Up @@ -96,10 +96,6 @@ def generate_reset_key
key
end

def bio
drupal_user.bio
end

def uid
drupal_user.uid
end
Expand Down
250 changes: 0 additions & 250 deletions app/views/users/_tags_form.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -87,255 +87,5 @@
</div>
</div>
</div>
<br />


<div class="control-group row">
<div class="col-md-3">
<label class="" for="location"><%= t('users._tags_form.location') %></label>
</div>
<div class="col-md-8">
<p><span id="location"></span></p>
<div class="input-group col-md-5">
<span class="input-group-addon"><i class="fa fa-map-marker"></i></span>
<input autocomplete="off" id="geo_location" name="info[location]" type="text" placeholder="<%= t('users._tags_form.type_location') %>" data-provide="typeahead" class="form-control ui-autocomplete-input" data-tag="location" />
</div>
<div class="input-group col-md-offset-6" style="margin-top: -33px;">
<a class="btn btn-default" id="myLocation">
<span class="glyphicon glyphicon-map-marker"><%= t('users._tags_form.map') %></span>
</a>
</div>
<div class="clearfix"></div><br />
</div>

<div class="col-md-3">
<label for="preference"><%= t('users._tags_form.location_privacy') %></label>
</div>
<div class="col-md-8">
<div class="input-group">
<input id="location_privacy" type="checkbox" name="privacy" <%= current_user.location_privacy ? "checked" : "" %>>
</div>
</div>
</div>
<br />


<div class="container">
<div id="location_map" class="row"></div>
</div>

<style type="text/css">
.hexbin-hexagon {
stroke: #000;
stroke-width: 1px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
// fetch geo location
<% if @location_tag %>

var geo_location = {
lat: <%= @location_tag.lat %>,
long: <%= @location_tag.lon %>,
}

// Display Map
$('#geo_location').attr("value", "<%= @location_tag.location %>");

$('#location_map').html("<div id='map' class='col-md-8' style='height:300px;'></div>");
window.map = L.map('map').setView([geo_location.lat, geo_location.long], 15) || {};
var mymap = window.map;
L.tileLayer("https://a.tiles.mapbox.com/v3/jywarren.map-lmrwb2em/{z}/{x}/{y}.png",{
attribution: "<a href='http://openstreetmap.org'>OSM</a> tiles by <a href='http://mapbox.com'>MapBox</a>"
}).addTo(mymap);

<% if current_user.location_privacy %>

var marker = L.marker([geo_location.lat, geo_location.long]).addTo(mymap);
marker.bindPopup("<b><%= @user.name %></b>").openPopup();

<% else %>
var lat = parseFloat(geo_location.lat).toFixed(4);
var long = parseFloat(geo_location.long).toFixed(4);

var options = {
radius : 20, // Size of the hexagons/bins
opacity: 0.5, // Opacity of the hexagonal layer
duration: 200, // millisecond duration of d3 transitions (see note below)
lng: function(d){ return d[1]; }, // longitude accessor
lat: function(d){ return d[0]; }, // latitude accessor
value: function(d){ return d.length; }, // value accessor - derives the bin value
valueFloor: 0, // override the color scale domain low value
valueCeil: undefined, // override the color scale domain high value
colorRange: ['#f7fbff', '#08306b'], // default color range for the heat map (see note below)
onmouseover: function(d, node, layer) {},
onmouseout: function(d, node, layer) {},
onclick: function(d, node, layer) {}
}

var hexlayer = L.hexbinLayer(options).addTo(mymap);
hexlayer.colorScale().range(["white", "grey"]);

hexlayer.data([[lat, long]]);

<% end %>

<% end %>

if ("geolocation" in navigator) {
$('#myLocation').click(function(e) {
initMap();
});
} else {
console.log("Geo Location not available in navaigator");
}

$('.tag-input').typeahead({
items: 8,
minLength: 3,
source: function(query, process) {
var key = $(this.$element[0]).data('tag')
return $.post('/profile/suggested/'+key+'/'+query, {}, function(data) {
return process(data)
});
},
updater: function(text) {
$(this).val(text)

}
});

$('.tag-input').keydown(function(e){
if(e.keyCode == 13) {
// Send ajax request
var type = $(this).data('tag');
var value = $(this).val();
var that = this;
$.ajax({
url: "/profile/tags/create/<%= @user.name %>",
type: 'POST',
data: {
'type': type,
'value': value
},
success: function(data) {
response = JSON.parse(data);
parent = $(that).parent().parent().parent()
if (response['errors'].length > 0) {
$(parent).children('.help-block').html("")
$(parent).addClass('has-error')
$(parent).append('<span class="help-block">'+response['errors']+'</span>')
}
else {
var type = response['saved'][1]
var tag = response['saved'][2]
var tag_id = response['saved'][0]
$(parent).children('.help-block').html("")
$(parent).removeClass('has-error')
$("#" + type).append("<span id='tag_"+tag_id+"' class='label label-primary' style='font-size:13px;margin-right: 4px;'>"+tag+" <a class='tagdelete' data-remote='true' href='/info/tags/delete/"+tag_id+"'>x</a></span> ");
$(that).val("");
}
},
error: function(error) {

}
});
}

});


$('.tagdelete').click(function(e){
e.preventDefault();
that = this
$.ajax({
url: $(this).attr('href'),
type: 'POST',
success: function(data) {
response = JSON.parse(data)
if (response.status) {
$(that).parent().html("")
}
}
})
});

});

function initMap() {

var lat, lon;
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
long = position.coords.longitude;

var mymap;
$('#location_map').html("<div id='map' class='col-md-8' style='height:300px;'></div>");
mymap = new L.map('map').setView([lat, long], 15);

L.tileLayer("https://a.tiles.mapbox.com/v3/jywarren.map-lmrwb2em/{z}/{x}/{y}.png",{
attribution: "<a href='http://openstreetmap.org'>OSM</a> tiles by <a href='http://mapbox.com'>MapBox</a>",
}).addTo(mymap);

<% if current_user.location_privacy %>

var marker = L.marker([lat, long]).addTo(mymap);
marker.bindPopup("<b><%= @user.name %></b>").openPopup();

<% else %>
lat = parseFloat(lat).toFixed(4);
long = parseFloat(long).toFixed(4);

var options = {
radius : 20, // Size of the hexagons/bins
opacity: 0.5, // Opacity of the hexagonal layer
duration: 200, // millisecond duration of d3 transitions (see note below)
lng: function(d){ return d[1]; }, // longitude accessor
lat: function(d){ return d[0]; }, // latitude accessor
value: function(d){ return d.length; }, // value accessor - derives the bin value
valueFloor: 0, // override the color scale domain low value
valueCeil: undefined, // override the color scale domain high value
colorRange: ['#f7fbff', '#08306b'], // default color range for the heat map (see note below)
onmouseover: function(d, node, layer) {},
onmouseout: function(d, node, layer) {},
onclick: function(d, node, layer) {}
}

var hexlayer = L.hexbinLayer(options).addTo(mymap);
hexlayer.colorScale().range(["white", "grey"]);

hexlayer.data([[lat, long]]);

<% end %>

$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long, function(data) {
if (data.status) {
var address = data.results[0].formatted_address;
$.ajax({
url: "/profile/location/create/<%= @user.name %>",
type: 'POST',
data: {
type: 'location',
value: {
address: address,
lat: lat,
long: long
}
},
success: function(data) {
response = data;
if (response.status) {
$("#geo_location").val(response.location.location);
console.log("Success");
}

}
});
}
});
});
}

</script>
</form>
2 changes: 1 addition & 1 deletion app/views/users/profile.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@
</small>
</h3>

<p><small><%= raw auto_link(RDiscount.new(@user.bio).to_html, :sanitize => false) %></small></p>
<p><small><%= raw auto_link(RDiscount.new(@profile_user.bio).to_html, :sanitize => false) %></small></p>

<br />

Expand Down
26 changes: 26 additions & 0 deletions db/migrate/20170704165711_add_user_bio_and_token.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class AddUserBioAndToken < ActiveRecord::Migration
def up
add_column :rusers, :bio, :text, limit: 2147483647, default: ''
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's odd; the error I'm seeing is:

Error: test_confirm_user_reset_key_not_visible_on_profile_to_non-admins(UsersControllerTest): ActionView::Template::Error: wrong argument type nil (expected String)
app/views/users/profile.html.erb:149:in `to_html'

that's on this line:

<p><small><%= raw auto_link(RDiscount.new(@profile_user.bio).to_html, :sanitize => false) %></small></p>

And @profile_user is a User as of this line: https://github.com/jywarren/plots2/blob/user-bio-and-token/app/controllers/users_controller.rb#L107

So, given this default, it should have a value of '', not nil. What's the deal?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm adding a unit test to ensure that a new User record has a non-nil bio.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jywarren I'll try to look into it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, okay. Yes, in the migration we set the default bio to '', right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, that's what's confusing!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apparently default values are not universally supported??? whoa. I'll try setting it manually.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using rails console?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jywarren Oh, the fixtures weren't updated?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ugh yeah. i should've done this all at once, locally, but i kept thinking it was a small fix.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jywarren I'm glad we have this sorted. What next for this PR?

add_column :rusers, :token, :string
add_column :rusers, :status, :integer, default: 0
remove_column :rusers, :location_privacy

# copy bios into new fields for non-spam users
DrupalUsers.where('status != 0').each do |u|
user = u.user
user.status = u.status
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right here you could do something like user.token = SecureRandom.hex

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jywarren okay, I am setting up plots2 again and will do this hopefully by today.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jywarren I don't think SecureRandom.hex will ensure uniqueness, though. What do you say?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to regenerate the schema file. Doing this now!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jywarren great.

user.bio = DrupalProfileValue.find_by_uid(user.id, conditions: { fid: 7 }) || ''
user.token = SecureRandom.uuid
user.save({})
end
drop_table :location_tags
drop_table :searches
end

def down
remove_column :rusers, :bio
remove_column :rusers, :token
remove_column :rusers, :status
add_column :rusers, :location_privacy, :boolean
end
end
Loading